How do I format a double to a string and only show decimal digits when necessary?

扶醉桌前 提交于 2019-11-27 22:15:49

问题


I have code like:

lblFranshizShowInvwNoskhehEdit.Text = string.Format("{0:n}",
    (double)(int.Parse(drDarman["FranshizDarsad"].ToString()) * 
        Convert.ToInt64(RadNumerictxtPayInvwNoskhehEdit.Text)) / 100);

But {0:n0} string format forces the label's text to not have decimal digits and {0:n} string format forces the label's text to have 2 decimal digits (default).

In my scenario I just want decimal digits when necessary / without rounding them / how can I do that?


回答1:


You can just do:

string.Format("{0}", yourDouble);

It will include only digits when necessary.

If you want other examples of formatting doubles to string check out this link.

EDIT: Based on your comment you want the , seperator so you could do:

string.Format("{0:0,0.########}", yourDouble);

Just put as many # for the max number of decimal places you want to show. It will only show the digits when necessary but up to the maximum digits based on how many # you include in the format. The # means only show a digit if necessary so if you give a number like 123 with no decimal, it will display as 1,234 but if you give it 1234.456, it will display as 1,234.456. If you go beyond the max digits you specified they will be rounded.

EDIT: To fix your double zero scenario just change it to:

string.Format("{0:#,0.########}", yourDouble);

That should work perfectly now :)




回答2:


this is mine :

string.Format("{0:n2}", double);


来源:https://stackoverflow.com/questions/3243440/how-do-i-format-a-double-to-a-string-and-only-show-decimal-digits-when-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!