What is the best way to format a decimal amount to string for UI display in the correct culture info?
Asked
Active
Viewed 2.5k times
11
-
1What'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 Answers
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
-
nHibernate property was Decimal? therefoer the format option was not available on toString method. Now creating decimal variable and using your answer and works a treat. cheers! – c00ke Feb 26 '10 at 13:34
-
if it's a Nullable
then you could either user the .Value property or cast to decimal (if you are sure it's not null) – Hans Kesting Feb 26 '10 at 15:10 -
-
1
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
5
use:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);

NetSide
- 3,849
- 8
- 30
- 41
-
3
-
JavaScript is not 'Global' aware, so I used .ToString("#.00", New CultureInfo("en-GB", False)) – Zymotik Mar 28 '12 at 13:52