gpt4 book ai didi

C# 将字符串转换为 double /十进制并返回字符串,保留尾随零,为千位添加逗号

转载 作者:太空狗 更新时间:2023-10-29 23:05:19 29 4
gpt4 key购买 nike

我正在尝试获取用户输入,解析它然后使用 String.Format() 显示,用逗号格式化数千个。

So, if user provides
1000 I will display 1,000
1000.00 => 1,000.00
1000.0 => 1,000.0
1,000.5 => 1,000.5

基本上,我想保留提供的所有小数(包括尾随零),并只为千位添加格式。我试过:

String.Format("{0:#,0.######}" , Decimal.Parse(input));
String.Format("{0:#,0.######}" , Double.Parse(input);

最佳答案

double.Parse(input) 是不行的,因为 double 不跟踪小数位数。

decimal.Parse(input).ToString() 将显示 decimal 确实会跟踪它。不幸的是,decimal.Parse(input).ToString() 使用此精度并且不使用千位分隔符,并且 decimal.Parse(input).ToString("N") 忽略精度但使用千位分隔符。

不过,手动从小数中提取精度是可行的,这允许您构建正确的格式字符串:

static string InsertThousandsSeparator(string input) {
var dec = decimal.Parse(input);
var bits = decimal.GetBits(dec);
var prec = bits[3] >> 16 & 255;
return dec.ToString("N" + prec);
}

这是基于the layout of decimal as described on MSDN :

Bits 16 to 23 must contain an exponent between 0 and 28, which indicates the power of 10 to divide the integer number.

See it working on .NET Fiddle. (由@Alisson 提供)

关于C# 将字符串转换为 double /十进制并返回字符串,保留尾随零,为千位添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45333030/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com