Display Float as String with at Least 1 Decimal Place

。_饼干妹妹 提交于 2019-12-17 07:47:10

问题


I want to display a float as a string while making sure to display at least one decimal place. If there are more decimals I would like those displayed.

For example: 1 should be displayed as 1.0 1.2345 should display as 1.2345

Can someone help me with the format string?


回答1:


Use ToString(".0###########") with as much # as decimals you want.




回答2:


This solution is similar to what other are saying, but I prefer to use string.Format. For example:

float myFloat1 = 1.4646573654;
float myFloat2 = 5;
Console.WriteLine(string.Format("Number 1 : {0:0.00##}", myFloat1));
Console.WriteLine(string.Format("Number 2 : {0:0.00##}", myFloat2));

// Newer Syntax
Console.WriteLine($"{myFloat1:0.00##}";
Console.WriteLine($"{myFloat2:0.00##}";

This would produce :

Number 1 : 1.4646
Number 2 : 5.00
Number 1 : 1.4646
Number 2 : 5.00



回答3:


Try this:

doubleNumber.ToString("0.0###");

And, for your reference (double ToString method): http://msdn.microsoft.com/en-us/library/kfsatb94.aspx




回答4:


float fNumber = 1.2345; // Your number
string sNumber = fNumber.ToString(); // Convert it to a string
If ((sNumber.Contains(".") == false) && (sNumber.Contains(",") == false)) // Check if it's got a point or a comma in it...
{
    sNumber += ".0"; // ... and if not, it's an integer, so we'll add it ourselves.
}


来源:https://stackoverflow.com/questions/8038994/display-float-as-string-with-at-least-1-decimal-place

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