C# 中的十进制 ToString() 转换问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16562496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:21:50  来源:igfitidea点击:

Decimal ToString() conversion issue in C#

c#stringdecimal

提问by Pushkar

I am facing a problem when I try to convert decimal?to string. Scenario is

当我尝试转换decimal?string. 情景是

decimal decimalValue = .1211;
string value = (decimalValue * 100).ToString();

Current Result : value = 12.1100

当前结果:值 = 12.1100

Expected Result : value = 12.11

预期结果:值 = 12.11

Please let me know, what could be reason for this.

请让我知道,这可能是什么原因。

采纳答案by Tim Schmelter

Decimalpreserves any trailing zeroes in a Decimalnumber. If you want two decimal places instead:

Decimal保留数字中的任何尾随零Decimal。如果你想要两位小数:

decimal? decimalValue = .1211m;
string value = ((decimal)(decimalValue * 100)).ToString("#.##")

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

or

或者

string value = ((decimal)(decimalValue * 100)).ToString("N2")

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

From System.Decimal:

来自System.Decimal

A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.

The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. Therefore, the binary representation of a Decimal value is of the form, ((-296to 296) / 10(0 to 28)), where -296-1 is equal to MinValue, and 296-1 is equal to MaxValue.

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, >>trailing zeroes can be revealed by the ToString method if an appropriate format string is applied<<.

十进制数是一个浮点值,由一个符号、一个数字值(该值中的每个数字的范围为 0 到 9)和一个比例因子组成,该比例因子指示分隔整数部分和小数部分的浮点小数点的位置的数值。

Decimal 值的二进制表示由 1 位符号、96 位整数和用于划分 96 位整数并指定它的哪一部分是十进制小数的比例因子组成。比例因子隐式是数字 10,上升到 0 到 28 之间的指数。因此,十进制值的二进制表示形式为 ((-2 96到 2 96) / 10 (0 到 28)) ,其中 -2 96-1 等于 MinValue,2 96-1 等于 MaxValue。

缩放因子还保留十进制数中的任何尾随零。尾随零不会影响算术或比较运算中十进制数的值。但是,如果应用了适当的格式字符串<<,ToString 方法可以显示 >> 尾随零。

Remarks:

评论:

  1. the decimal multiplication needs to be casted to decimal, because Nullable<decimal>.ToStringhas no format provider
  2. as Chris pointed out you need to handle the case that the Nullable<decimal>is null. One way is using the Null-Coalescing-Operator:

    ((decimal)(decimalValue ?? 0 * 100)).ToString("N2")
    
  1. 十进制乘法需要转换为十进制,因为Nullable<decimal>.ToString没有格式提供程序
  2. 正如克里斯指出的那样,您需要处理Nullable<decimal>is的情况null。一种方法是使用Null-Coalescing-Operator

    ((decimal)(decimalValue ?? 0 * 100)).ToString("N2")
    

This article from Jon Skeet is worth reading:

Jon Skeet 的这篇文章值得一读:

Decimal floating point in .NET(seach for keeping zeroesif you're impatient)

.NET 中的十进制浮点数(如果您不耐烦,请搜索以保持零

回答by Soner G?nül

Since you using Nullable<T>as your decimal, Nullable<T>.ToString()method doesn't have overloading takes parameters that you can use for formatting.

由于您使用Nullable<T>as your decimal,Nullable<T>.ToString()方法没有重载可用于格式化的参数。

Instead of, you can explicitly cast it to decimaland you can use .ToString()method for formatting.

相反,您可以将其显式转换为,decimal并且可以使用.ToString()方法进行格式化。

Just use "0.00"format in your .ToString()method.

只需"0.00"在您的.ToString()方法中使用格式。

decimal? decimalValue = .1211M;
string value = ((decimal)(decimalValue * 100)).ToString("0.00");
Console.WriteLine(value);

Output will be;

输出将是;

12.11

Here is a DEMO.

这是一个DEMO.

As an alternative, you can use Nullable<T>.Valuewithout any conversation like;

作为替代方案,您可以在Nullable<T>.Value没有任何对话的情况下使用;

string value = (decimalValue * 100).Value.ToString("0.00");

Check out for more information from Custom Numeric Format Strings

查看更多信息来自 Custom Numeric Format Strings

回答by emre nevayeshirazi

String.Format("{0:0.00}", decimalValue * 100);

You can use .Format()as an alternative to .ToString("0.00").

您可以将其.Format()用作 ) 的替代.ToString("0.00"

回答by Davio

Alternatively, you can specify the format "F2", like so: string val = decVal.ToString("F2")as this specifies 2 decimal places.

或者,您可以指定格式“F2”,如下所示:string val = decVal.ToString("F2")因为这指定了 2 个小数位。

回答by Mudassir Hasan

Use the fixed-point ("F) format specifier.

使用定点 ("F) 格式说明符

   string value = (decimalValue * 100).ToString("F");

The default precision specifier is based on value of NumberFormatInfo.NumberDecimalDigitsproperty which by default has value 2. So if don't specify a digit aftyer "F" , it by default specifies two decimal digits.

默认精度说明符基于NumberFormatInfo.NumberDecimalDigits属性的值,默认值为 2。因此,如果在 "F" 后不指定数字,则默认指定两个十进制数字。

F0 - No decimal places
F1 - One decimal place

回答by Chris Sinclair

Since decimal?does not have a ToString(string format)overload, the easiest way is to use String.Formatinstead which will provide consistent results with the nullcase for decimalValueas well (resulting in an empty string) when compared to your original code:

由于decimal?没有ToString(string format)重载,最简单的方法是使用String.Format它,与原始代码相比,它也将提供与null案例一致的结果decimalValue(导致空字符串):

string value = String.Format("{0:#.##}", decimalValue * 100);

But there are some other considerations for other numbers that you weren't clear on.

但是对于您不清楚的其他数字,还有其他一些考虑因素。

If you have a number that does not produce a value greater than 0, does it show a leading zero? That is, for 0.001211, does it display as 0.12or .12? If you want the leading zero, use this instead (notice the change from #.##to 0.##):

如果您有一个不产生大于 0 的值的数字,它是否显示前导零?也就是说,对于0.001211,它是否显示为0.12.12?如果您想要前导零,请改用它(注意从#.##到的更改0.##):

string value = String.Format("{0:0.##}", decimalValue * 100);

If you have more than 2 significant decimal places, do you want those displayed? So if you had .12113405would it display as 12.113405? If so use:

如果您有 2 个以上的有效小数位,您是否希望显示这些小数位?所以如果你有.12113405它会显示为12.113405?如果是这样,请使用:

string value = String.Format("{0:#.############}", decimalValue * 100);

(honestly, I think there must be a betterformatting string than that, especially as it only supports 12 decimal places)

(老实说,我认为必须有比这更好的格式化字符串,尤其是因为它只支持 12 位小数)

And of course if you want both leading zeros andmultiple decimal places, just combine the two above:

当然,如果您想要前导零多个小数位,只需将以上两个结合起来:

string value = String.Format("{0:0.############}", decimalValue * 100);

回答by John Willemse

In case you do not want to limit to a certain amount of decimal digits:

如果您不想限制为一定数量的十进制数字:

decimal? decimalValue = .1211;
string value = decimalValue == null 
               ? "0"
               : decimalValue == 0
               ? "0"
               : (decimalValue * 100).ToString().TrimEnd('0');

This will trim any (if any) trailing zeroes of the string and also return "0" if decimalValueis null. If the value is 0 then "0" is returned without trimming.

这将修剪字符串的任何(如果有)尾随零,如果decimalValue为空,也返回“0” 。如果值为 0,则返回“0”而不进行修整。