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

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

问题描述

可以说,我有一个3.4679的价值和希望3.46,我怎么能截断到小数点后两位,如果没有四舍五入?

我曾尝试以下,但所有三个给我3.47:

 无效的主要()
{
    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,但似乎只是脏一些如何:

 无效的主要()
{
    Console.Write(Math.Round(3.46799999999 -.005,2));
}


解决方案

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

要小心,像这样的分数不能准确重于浮点psented $ P $。

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?

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

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天全站免登陆