Display Float as String with at Least 1 Decimal Place

前端 未结 4 1674
野的像风
野的像风 2020-11-30 12:30

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:

4条回答
  •  Happy的楠姐
    2020-11-30 12:55

    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
    

提交回复
热议问题