C#双格式的小数点对齐 [英] C# double formatting align on decimal sign

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

问题描述

我对准各种小数位数的号码,这样在小数点上的直排对齐。这可以通过用空格填充来achevied,但我有麻烦了。



乐事说我要对齐的以下数字:
0
0.0002
0.531
2.42
12.5
123.0
123172



这是结果后我:

  0 
0.0002
0.531
2.42
12.5
123.0
123172


解决方案

如果你想正是这种结果你不能用数字数据的任何格式,因为这将不格式化 123 123.0 。你必须把该值作为字符串保存尾随零



这让你正是你要的结果是:



 的String []号= {0,0.0002,0.531,2.42,12.5,123.0,123172}; 

的foreach(在数字串号){
INT POS = number.IndexOf('。');
如果(POS == -1)= POS number.Length;
Console.WriteLine(新字符串('',6 - POS)+电话号码);
}



输出:

  0 
0.0002
0.531
2.42
12.5
123.0
123172


I align numbers with various number of decimals so that the decimal sign aligns on a straight row. This can be achevied by padding with spaces, but I'm having trouble.

Lays say I want to align the following numbers: 0 0.0002 0.531 2.42 12.5 123.0 123172

This is the result I'm after:

     0
     0.0002
     0.531
     2.42
    12.5
   123.0
123172

解决方案

If you want exactly that result you can't use any formatting of numerical data, as that would not format 123 as 123.0. You have to treat the values as strings to preserve the trailing zero.

This gives you exactly the result that you asked for:

string[] numbers = { "0", "0.0002", "0.531", "2.42", "12.5", "123.0", "123172" };

foreach (string number in numbers) {
  int pos = number.IndexOf('.');
  if (pos == -1) pos = number.Length;
  Console.WriteLine(new String(' ', 6 - pos) + number);
}

Output:

     0
     0.0002
     0.531
     2.42
    12.5
   123.0
123172

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

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