舍去在C#2位小数 [英] Rounding down to 2 decimal places in c#

查看:1093
本文介绍了舍去在C#2位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以繁殖两位小数和圆形的结果下降到2位小数?



例如,如果方程为41.75×0.1的结果将是4.175。如果我做这在C#与小数它会自动四舍五入到4.18。我想向下舍至4.17。



我尝试使用Math.Floor但它只是向下取整为4.00。下面是一个例子:

  Math.Floor(41.75 * 0.1); 


解决方案

Math.Round( ...)函数有一个枚举告诉它使用什么四舍五入策略。不幸的是这两个定义将不完全适合您的情况



这两个中点舍入模式为:




  1. AwayFromZero - 当一个数是中间两个人之间的,它向着那就是远离零最接近的数字四舍五入。 (阿卡,四舍五入)

  2. ToEven - 当一个数是中间两个人之间,它向最接近的偶数舍入。 (将有利于在0.16 0.17,和0.18以上0.17)



您想要使用什么是地板一些乘法。

  VAR输出= Math.Floor((41.75 * 0.1)* 100)/ 100; 



输出变量应该有4.17在这现在



其实你也可以写一个函数采取可变长度,以及:

 公共小数ROUNDDOWN(十进制我,双小数位数)
{
无功功率= Math.Pow(10,小数位数);
返回Math.Floor(我*电源)/电源;
}


How can I multiply two decimals and round the result down to 2 decimal places?

For example if the equation is 41.75 x 0.1 the result will be 4.175. If I do this in c# with decimals it will automatically round up to 4.18. I would like to round down to 4.17.

I tried using Math.Floor but it just rounds down to 4.00. Here is an example:

Math.Floor (41.75 * 0.1);

解决方案

The Math.Round(...) function has an Enum to tell it what rounding strategy to use. Unfortunately the two defined won't exactly fit your situation.

The two Midpoint Rounding modes are:

  1. AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero. (Aka, round up)
  2. ToEven - When a number is halfway between two others, it is rounded toward the nearest even number. (Will Favor .16 over .17, and .18 over .17)

What you want to use is Floor with some multiplication.

var output = Math.Floor((41.75 * 0.1) * 100) / 100;

The output variable should have 4.17 in it now.

In fact you can also write a function to take a variable length as well:

public decimal RoundDown(decimal i, double decimalPlaces)
{
   var power = Math.Pow(10, decimalPlaces);
   return Math.Floor(i * power) / power;
}

这篇关于舍去在C#2位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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