截断号指定的小数位 [英] Truncating a number to specified decimal places
问题描述
我需要截断一个数字来2位小数,这基本上意味着
斩去额外的数字
I need to truncate a number to 2 decimal places, which basically means chopping off the extra digits.
例如:
2.919 -> 2.91
2.91111 -> 2.91
为什么呢?这就是存储数量
特定精度当SQL Server在做什么。例如,如果一个列是小数(8,2),并尝试
插入/更新多项9.1234,3和4将被砍掉。
Why? This is what SQL server is doing when storing a number of a particular precision. Eg, if a column is Decimal(8,2), and you try to insert/update a number of 9.1234, the 3 and 4 will be chopped off.
我需要做同样的事情在C#代码
I need to do exactly the same thing in c# code.
这是我能想到这样做是不是唯一可能的方式:
The only possible ways that I can think of doing it are either:
使用stringformatter到打印出来只有
两个小数位,然后将其转换为一个小数,
如
Using the stringformatter to "print" it out only two decimal places, and then converting it to a decimal, eg:
decimal tooManyDigits = 2.1345
decimal ShorterDigits = Convert.ToDecimal(tooManyDigits.ToString("0.##"));
// ShorterDigits is now 2.13
我不开心与此因为它涉及到字符串,然后
另一个字符串到十进制的转换,这似乎有点疯狂。
I'm not happy with this because it involves a to-string and then another string to decimal conversion which seems a bit mad.
使用Math.Truncate(只接受一个整数),所以我
可以用100乘以它,截断它,然后乘以100除以例如:
Using Math.Truncate (which only accepts an integer), so I can multiply it by 100, truncate it, then divide by 100. eg:
decimal tooLongDecimal = 2.1235;
tooLongDecimal = Math.Truncate(tooLongDecimal * 100) / 100;
我也不会满意这个,因为如果tooLongDecimal为0,
我会由0误差得到一个鸿沟。
I'm also not happy with this because if tooLongDecimal is 0, I'll get a divide by 0 error.
当然,有一个更好的+更简单的方法! ?任何建议
Surely there's a better + easier way! Any suggestions?
推荐答案
您已经回答了自己的问题;看来你只是零手段误解了分裂。要做到这一点,正确的方法是倍增,截断,然后devide,像这样的:
You've answered the question yourself; it seems you just misunderstood what division by zero means. The correct way to do this is to multiply, truncate, then devide, like this:
decimal TruncateTo100ths(decimal d)
{
return Math.Truncate(d* 100) / 100;
}
TruncateTo100ths(0m); // 0
TruncateTo100ths(2.919m); // 2.91
TruncateTo100ths(2.91111m); // 2.91
TruncateTo100ths(2.1345m); // 2.13
有没有被零除这里,仅存在由100划分,这是完全安全的。
There is no division by zero here, there is only division by 100, which is perfectly safe.
这篇关于截断号指定的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!