How to display two digits after decimal every time

2019-08-19 03:20发布

问题:

This question already has an answer here:

  • Leave only two decimal places after the dot 13 answers

I have a process, in which client want me to always display amount with two decimals either have value with decimal or not

example: if 17 then i want to display "17.00" and if 17.2 then i want to display "17.20" or if 17.2033 then i want to display "17.20" i have tried String.Format("{0:.##}", rec.Rate)

it does not works, please help me how can i do it.. thanks in advance

回答1:

try

double num=17.2;
string str=num.toString("0.00");

or this one.

double num=17.2;
string str=num.toString("N2");


回答2:

Try This:

double d=23.45;//any value here
String s=d.ToString("N2");


回答3:

Please check out this similar answer:

Leave only two decimal places after the dot

Check out what each of these return :

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

String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"


回答4:

You should use String.Format("{0:.##}", rec.Rate).

From MSDN:

0 - Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

#-Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.