浮点定长数字格式化c# [英] Floating Point fixed length Number formatting c#

查看:100
本文介绍了浮点定长数字格式化c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 C# 中按如下方式格式化浮点数,以便 C# 中浮点数的整个宽度是固定长度(python 等效格式说明符 6.2f)我不希望它用 0 填充左边但用空格填充

I want to format a floating point number as follows in C# such that the entire width of the floating point number in C# is a fixed length (python equivalent format specifier 6.2f) I do NOT want it to be padded with 0's on the left but padded with a white space

100.00
 90.45
  7.23
  0.00

到目前为止我尝试了什么

what I have tried so far

string.Format({0:###.##},100); 
string.Format({0:###.##},90.45);
string.Format({0:###.##},7.23);
string.Format({0:###.##},0.00);

但输出不正确

100
90.45
7.23
      //nothing is printed

我也经历过this 但我无法找到解决方案.我知道 string.PadLeft 方法,但我想知道是否有比

I have also gone through this but am unable to find a solution. I am aware of the string.PadLeft method, but I am wondering if there is a more proper way than

(string.format({0,0.00},number)).PadLeft(6," ")

编辑我特别问是否有正确的内置方法,而不是是否可以用相同的数学魔法来完成

EDIT I am specifically asking if there is a correct inbuilt method for the same, not if it can be done with same mathematical wizardry

推荐答案

如果你总是想要小数点后 2 位数字,你可以在格式说明符中指定 00.您还需要使用右对齐的字段宽度(我使用 6 作为最大字段宽度).

If you always want 2 digits after the decimal, you can specify 00 in the format specifier. You would need to use a right aligned field width also (I used 6 as the max field width).

试试这个:

void Main()
{
    Console.WriteLine(string.Format("{0,6:##0.00}",100.0)); 
    Console.WriteLine(string.Format("{0,6:##0.00}",90.45));
    Console.WriteLine(string.Format("{0,6:##0.00}",7.23));
    Console.WriteLine(string.Format("{0,6:##0.00}",0.00));
}

在 LinqPad 中输出:

In LinqPad it outputs:

100.00
 90.45
  7.23
  0.00

这篇关于浮点定长数字格式化c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆