Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When converting double to string, how can I round it up to N decimal places in C#? [duplicate]

Possible Duplicate:
Round a double to 2 significant figures after decimal point

I need at most N decimals, no more, but I don't want trailing zeroes. For example, if N = 2 then

15.352
15.355
15.3
15

should become (respectively)

15.35
15.36
15.3
15

like image 951
Nikola Novak Avatar asked Dec 09 '22 04:12

Nikola Novak


2 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 paramater for round is for you to specify how many decimal places to round to. It will round up by default.

like image 149
aevanko Avatar answered Dec 11 '22 17:12

aevanko


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

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

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

like image 43
Andrii Startsev Avatar answered Dec 11 '22 16:12

Andrii Startsev