如何圆形双值,但保留尾随零 [英] How to round double values but keep trailing zeros
问题描述
在C#我要舍入一个给定的双至小数点后一定量的函数。我总是希望我的功能与小数的一定量返回值(可以是一个字符串)。
In C# I want a function that rounds a given double to a given amount of decimals. I always want my function to return a value (which can be a string) with the given amount of decimals. If necessary, trailing zeros need to be added.
Example:
例>字符串结果= MyRoundingFunction(1.01234567,3);
//这必须返回1.012
string result = MyRoundingFunction(1.01234567, 3);
// this must return "1.012"
这很简单,它只是四舍五入并转换到串。但这里谈到的问题:
That's easy, it's just rounding and converting to string. But here comes the problem:
string result2 = MyRoundingFuntion(1.01, 3);
// this must return "1.010"
有没有做一个方便/标准方法这一点,或者我需要手动添加尾随零?
Is there a convenient/standard way to do this, or do I manually need to add trailing zeros?
任何帮助表示赞赏。需要注意的是在现实生活中的应用我不能硬编码的小数位数。
Any help is appreciated. Note that in the real life application I can't hard code the number of decimals.
推荐答案
您可以创建一个这样的例子格式化:
You can create a formatter like this example:
int numDigitsAfterPoint = 5;
double num = 1.25d;
string result = num.ToString("0." + new string('0', numDigitsAfterPoint));
或(更容易)
string result = num.ToString("F" + numDigitsAfterPoint);
一点题外话,的ToString
使用 MidpointRounding.AwayFromZero
而不是 MidpointRounding.ToEven
(也称为银行家四舍五入)。作为一个例子:
As a sidenote, ToString
uses the MidpointRounding.AwayFromZero
instead of the MidpointRounding.ToEven
(also called Banker's Rounding). As an example:
var x1 = 1.25.ToString("F1");
var x2 = 1.35.ToString("F1");
var x3 = Math.Round(1.25, 1).ToString();
var x4 = Math.Round(1.35, 1).ToString();
这会产生不同的结果(因为 Math.Round
通常使用 MidpointRounding.ToEven
)
These will produce different result (because Math.Round
normally uses MidpointRounding.ToEven
)
和注意,内部的ToString()
似乎舍入位之前做一些神奇。对于双打,如果你问他不到15位,我认为它四舍五入到前15位数字,然后舍入到的数字权数。看到这里 https://ideone.com/ZBEis9
And note that internally ToString()
seems to do some "magic" before rounding digits. For doubles, if you ask him less than 15 digits, I think it rounds to 15 digits first and then rounds to the right number of digits. See here https://ideone.com/ZBEis9
这篇关于如何圆形双值,但保留尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!