Question

I can't format decimal in custom formatted string

0.656 => 0.67; 
23.656 => 23.67;
5105.54 => 5 105.54;
1234567,89 => 1 234 567,89

I found several posts:

c# - Using String Format to show decimal upto 2 places or simple integer

c# - Converting Decimal to string with non-default format

but when try to use them getting several problem

for example: on value

0.656 i'm getting ".656" or ".66"

23.656 => " 23.656" or " 23.66"

Car someone recommend links where I can find formatstring rules?

Was it helpful?

Solution

I don't think you actually want to convert 0.656 to 0.67, cause it is just wrong. I guess you mean it should display as 0.66

Use

YourNumber.ToString("0.##");

If you really want to have spaces (which again i think it is wrong):

YourNumber.ToString("#,##0.##").Replace("."," ")

OTHER TIPS

Give this a good read:

Custom Numeric Format Strings

You can use String.Format or ToString() overloades to achieve your goal.

If you want to format a number as a currency value, use this

var d = 0.656;
Console.WriteLine("{0:C}", d); // prints "€ 0,66", in my case

Make sure your localization settings give you the correct currency symbol and decimal character, I.E. a point or a comma.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top