Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format decimal value to currency with 2 decimal places [duplicate]

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.

like image 735
user3237078 Avatar asked Jan 30 '14 18:01

user3237078


1 Answers

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
like image 87
Alexei Levenkov Avatar answered Sep 30 '22 07:09

Alexei Levenkov