11

What is the best way to format a decimal amount to string for UI display in the correct culture info?

johnnyRose
  • 7,310
  • 17
  • 40
  • 61
c00ke
  • 2,245
  • 5
  • 26
  • 34
  • 1
    What's wrong with `myDecimal.ToString()`? – Joey Feb 26 '10 at 12:59
  • Loading nHibernate object from database, property is decimal and when call toString() it does format with correct decimal places. However when saving setting the same property from text eg. allocation.Price = Decimal.Parse(price, CultureInfo.CurrentCulture); but once this is set and call allocation.Price.toString() decimal places not added. eg after decimal parse 15 want 15.00 but toString just gives 15. Strange? – c00ke Feb 26 '10 at 13:04

4 Answers4

11

Add a format to the ToString: myDecimal.ToString("#.00") or myDecimal.ToString("C").

For a nullable decimal (decimal?) you will need to use the .Value property (myNullableDecimal.Value.ToString("C")) or cast the value to a plain (non-nullable) decimal. Be sure not to do this when the value is null or you will get an exception!

See the documentation for Standard or Custom numeric format strings.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
8

Why not decimalVar.ToString("F2", CultureInfo.CurrentCulture);. For format strings (the "F2" part) and what they do, see Standard Numeric Format Strings and Custom Numeric Format Strings

Philip Rieck
  • 32,368
  • 11
  • 87
  • 99
6

Also, if you want to use a culture specified by the user you can use:


string userInfo = "en-US";

yourDecimal.ToString("N2", CultureInfo.CreateSpecificCulture(userInfo));

or

yourDecimal.ToString("N2", new CultureInfo(userInfo));
MJ Vakili
  • 2,798
  • 1
  • 19
  • 25
Derek J.
  • 1,400
  • 1
  • 14
  • 23
5

use:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
NetSide
  • 3,849
  • 8
  • 30
  • 41