Format decimal to string in correct culture info
Asked Answered
I

4

13

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

Incorporator answered 26/2, 2010 at 12:56 Comment(2)
What's wrong with myDecimal.ToString()?Knowhow
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?Incorporator
M
12

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.

Mitre answered 26/2, 2010 at 13:25 Comment(4)
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!Incorporator
if it's a Nullable<decimal> then you could either user the .Value property or cast to decimal (if you are sure it's not null)Weep
the link is brokenFlush
@WeaponX - fixed. Thanks for the heads-up.Weep
G
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

Goerke answered 26/2, 2010 at 13:26 Comment(0)
R
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));
Rightist answered 9/10, 2015 at 19:46 Comment(0)
V
5

use:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
Vietnamese answered 26/2, 2010 at 12:59 Comment(2)
so what? He is not asking for dynamic cultureInfo.Vietnamese
JavaScript is not 'Global' aware, so I used .ToString("#.00", New CultureInfo("en-GB", False))Mathis

© 2022 - 2024 — McMap. All rights reserved.