How to convert double to string, how can I round it to N decimal places in C #?

Possible duplicate:
Radius of doubling to 2 significant digits after the decimal point

I need no more than N decimal places, no more, but I do not need trailing zeros. For example, if N = 2, then

15,352
15.355
15.3
fifteen

should become (respectively)

15.35
15.36
15.3
fifteen

+4
source share
3 answers

Try Math.Round(value, 2).ToString()

 Math.Round(15.352, 2).ToString(); //15.35 Math.Round(15.355, 2).ToString(); //15.36 Math.Round(15.3, 2).ToString(); //15.3 Math.Round(15.0, 2).ToString(); //15 

The second parameter for the round is to indicate how many decimal places to round to. By default it will be rounded.

+6
source

This can be done using a custom format string such as "0. ##", which displays a maximum of two decimal places.

 String.Format("{0:0.##}", 123.4567); // "123.46" 

Link: http://www.csharp-examples.net/string-format-double/

+5
source

Google really leads: use ## to skip leading zeros in the format string.

 // max. two decimal places String.Format("{0:0.##}", 123.4567); // "123.46" String.Format("{0:0.##}", 123.4); // "123.4" String.Format("{0:0.##}", 123.0); // "123" 
+2
source

Source: https://habr.com/ru/post/1383163/


All Articles