C#将字符串转换为双精度/十进制并返回字符串,保持尾随零,为数千添加逗号 [英] C# Convert string to double/decimal and back to string, keeping trailing zeroes, adding comas for thousands

查看:259
本文介绍了C#将字符串转换为双精度/十进制并返回字符串,保持尾随零,为数千添加逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取用户输入,对其进行解析,然后使用String.Format()进行显示,用逗号分隔成千上万的格式.

I am trying to get user input, parse it and then display with String.Format(), formatting thousands with comas.

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

基本上,我想保留提供的所有小数(包括尾随零),并仅添加成千上万的格式. 我试过了:

Basically I want to keep all decimals(including trailing zeroes) that were provided and just add formatting for thousands. I tried:

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

推荐答案

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

double.Parse(input) is a no go, as double does not keep track of the number of decimals.

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

decimal.Parse(input).ToString() will show that decimal does keep track of that. Unfortunately, decimal.Parse(input).ToString() uses this precision and doesn't use a thousands separator, and decimal.Parse(input).ToString("N") ignores the precision but does use a thousands separator.

虽然可以手动从十进制提取精度,但可以构建正确的格式字符串:

Manually extracting the precision from the decimal works though, and that allows you to build the correct format string:

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);
}

这基于 MSDN上所述的decimal布局:

第16到23位必须包含0到28之间的指数,这表示10的幂可以除以整数.

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

查看它在.NET Fiddle上的工作情况.(由@Alisson提供)

See it working on .NET Fiddle. (courtesy of @Alisson)

这篇关于C#将字符串转换为双精度/十进制并返回字符串,保持尾随零,为数千添加逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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