截断两位小数而不四舍五入 [英] Truncate Two decimal places without rounding

查看:26
本文介绍了截断两位小数而不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个值 3.4679 并且想要 3.46,我怎样才能在不四舍五入的情况下截断到两位小数?

Lets say I have a value of 3.4679 and want 3.46, how can I truncate to two decimal places that without rounding up?

我尝试了以下方法,但三个都给了我 3.47:

I have tried the following but all three give me 3.47:

void Main()
{
    Console.Write(Math.Round(3.4679, 2,MidpointRounding.ToEven));
    Console.Write(Math.Round(3.4679, 2,MidpointRounding.AwayFromZero));
    Console.Write(Math.Round(3.4679, 2));
}

这将返回 3.46,但在某些方面看起来很脏:

This returns 3.46, but just seems dirty some how:

void Main()
{
    Console.Write(Math.Round(3.46799999999 -.005 , 2));
}

推荐答案

value = Math.Truncate(100 * value) / 100;

请注意,像这样的分数不能用浮点数准确表示.

Beware that fractions like these cannot be accurately represented in floating point.

这篇关于截断两位小数而不四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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