Format decimal value in currency with two decimal places

I get data from a csv file and parse it in my application. In my csv file, I have a price column, the value of which I use, of course, in the price of an item in my project.

However, the price in the csv file does not contain a trailing 0, for example, if the price and element are $5.00 , then the csv file has it as $5 , if the price is $9.60 , csv has it as $9.6 . Other prices, such as $9.56 , are good, though.

This is how I get the price from the csv file:

  Price = string.IsNullOrEmpty(columns[3].Trim()) ? null : (decimal?)decimal.Parse(columns[3]), 

public decimal? Price { get; set; } my class price set to public decimal? Price { get; set; } public decimal? Price { get; set; } 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 this but did not work.

How to fix this so that csv values ​​like $5.9 formatted at $5.90 .

EDIT:

I tried:

 Price=decimal.Round(string.IsNullOrEmpty(columns[3].Trim()) ? null : (decimal?)decimal.Parse(columns[3]), 2, MidpointRounding.AwayFromZero); 

Not sure if I did it right?

Also, I'm not sure how I can use the option below in my code:

 decimalVar.ToString ("#.##"); 

Also tried:

  Price = string.IsNullOrEmpty(columns[3].Trim()) ? null : (decimal?)decimal.Parse(columns[3], NumberStyles.Currency) 

But still does not work.

+7
c # string-formatting
source share
3 answers

You are looking for "0:C2" see Standard Number Format Strings

Accuracy specifier: number of decimal digits

Example:

  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 
+15
source share

decimal do not have a "format" - they are just a number. It looks like you are trying to β€œassign” a format to the Price column, which you cannot do. Based on your first code example, it seems like you can easily parse CSV input with decimal precision.

You can choose a format when you display a value that you did not indicate where this happens. In the application? report? another csv?

+1
source share

This answer assumes your local currency symbol is $ .

Use Decimal.Parse(String, NumberStyles) to Decimal.Parse(String, NumberStyles) string, for example:

 string priceFromCsv = "$5"; var priceAsDecimal = Decimal.Parse(priceFromCsv, NumberStyles.Currency); 

Then use Decimal.ToString(String) with the format "C" to return to the fully formed currency, i.e.

 priceAsDecimal.ToString("C"); 

This will give you a fully formed currency with the correct number of decimal places.

0
source share

All Articles