简体   繁体   中英

String.format for removing zero after decimal

String.Format("{0:0}",100.00) // Should show as 100 // This works fine
String.Format("{0:0}",0.5) // Should show as 0.5

But above String.Format("{0:0}" does not work.

如果分别需要1000.5 ,我认为最简单的String.Format("{0}", myDouble )甚至myDouble.ToString()都可以工作。

You can use this format:

string.Format("{0:0.#####}", 0.5m)

This presumes that the number cannot have more than 5 decimal places.

Another way is to use the General ("G") Format Specifier :

string.Format("{0:G29}", 0.5m)

I think that you must use String.Format("{0: N2 }", your_number ). You only need to change N2 to N1 or N0 or whatever depending on how many decimals you want to display

I just tried with simple "{0}" as following
Console.WriteLine(String.Format("{0}",100.00));
Console.WriteLine(String.Format("{0}",0.5));
these result as you required. https://dotnetfiddle.net/J3FfOm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM