获取不舍入的最后2个小数位 [英] Get Last 2 Decimal Places with No Rounding

查看:56
本文介绍了获取不舍入的最后2个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我试图不加舍入地获得双精度的最后两个小数位。我尝试了从 Math.Floor Math.Truncate 的所有操作,但没有任何作用。

In C#, I'm trying to get the last two decimal places of a double with NO rounding. I've tried everything from Math.Floor to Math.Truncate and nothing is working.

我想要的结果样本:

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

将小数点右移两位,转换为整数以截断,将其移回左侧两个位置。框架中也可能有一些方法可以实现,但我现在无法看。您可以将其推广:

Move the decimal two places to the right, cast to an int to truncate, shift it back to the left two places. There may be ways in the framework to do it too, but I can't look right now. You could generalize it:

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

这篇关于获取不舍入的最后2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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