I am getting data from a csv file and parsing it to my application. In my csv file I have a column price
whose value I use as of course the price of an item in my project.
However, the price in the csv file does not contain trailing 0s,
For example, if the price of and item is $5.00
, the csv file has it as $5
, if the price is $9.60
, the csv has it as $9.6
. Other prices such as $9.56
are fine though.
This is how I retrieve the price from the csv file:
Price = string.IsNullOrEmpty(columns[3].Trim()) ?
null : (decimal?)decimal.Parse(columns[3]),
In my class Price
is set as public decimal? Price { get; set; }
.
How do I format what is returned to fix this problem?
Price = String.Format("Price: {0:C}",
string.IsNullOrEmpty(columns[3].Trim()) ?
null : (decimal?)decimal.Parse(columns[3]));
I tried the above but didn't work.
How do I fix it so that values in the csv as $5.9
are formatted to $5.90
.
EDIT:
Tried:
Price=decimal.Round(string.IsNullOrEmpty(columns[3].Trim()) ?
null :
(decimal?)decimal.Parse(columns[3]), 2, MidpointRounding.AwayFromZero);
Not sure if I did that right?
Also, I'm not certain how I can use the below option in my code:
decimalVar.ToString ("#.##");
Also tried:
Price = string.IsNullOrEmpty(columns[3].Trim()) ?
null : (decimal?)decimal.Parse(columns[3], NumberStyles.Currency)
But still doesn't work.
You are looking for "0:C2"
see Standard Numeric Format Strings
Precision specifier: Number of decimal digits
Sample:
String.Format("{0:C2}", 5d); //results in $5.00
String.Format("{0:C2}", 5.9d); //results in $5.90
String.Format("{0:C2}", 5.123d); //results in $5.12
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With