在 C# 中,我试图获取没有四舍五入的 double 的最后两位小数。我已经尝试了从 Math.Floor
到 Math.Truncate
的所有方法,但没有任何效果。
我想要的结果示例:
1,424.2488298 -> 1,424.24
53.5821 -> 53.58
10,209.2991 -> 10,209.29
有什么想法吗?
最佳答案
嗯,数学上很简单:
var f = 1.1234;
f = Math.Truncate(f * 100) / 100; // f == 1.12
将小数点向右移动两位,转换为 int 进行截断,再向左移两位。框架中可能也有方法可以做到这一点,但我现在看不到。你可以概括它:
double Truncate(double value, int places)
{
// not sure if you care to handle negative numbers...
var f = Math.Pow( 10, places );
return Math.Truncate( value * f ) / f;
}
关于c# - 获取最后 2 位小数,不四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931795/