格式化十进制变量 [英] To format the decimal variable
问题描述
我该如何格式化十进制变量?
假设
我声明了十进制类型变量i = 0;
我是6.1056.
其实我想得到的值是6.11
我将如何解决以上问题???
请帮助我....
How can i format the decimal variable??
Suppose,
I declare decimal type variable i = 0;
and i is 6.1056.
Actually I want to get the value is 6.11
how will i do above problem????
Please help me....
推荐答案
看看 ^ ]
Have a look at Math.Round [^]
decimal a = 1.994444M;
Math.Round(a, 2); //returns 1.99
来自 http://stackoverflow.com /questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c [ ^ ]
from http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c[^]
尝试一下
Try this
i = Math.Round(6.1056,2);
如解决方案1和2所述,此处解释了Math
类的Round
方法
Math.Round方法(十进制,Int32,MidpointRounding) [
As already given in Solution 1 and 2, theRound
method ofMath
class explained here
Math.Round Method (Decimal, Int32, MidpointRounding)[^]
can be used as follows:
decimal number = 6.1056M;
Console.WriteLine (Math.Round(number,2));
默认情况下,Round
方法使用此处解释的MidpointRounding.ToEven
枚举值 http://msdn.microsoft .com/en-us/library/system.midpointrounding.aspx [
By default the Round
method uses MidpointRounding.ToEven
enumeration value explained here http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx[^], which means that if the value to be rounded is 6.105
it will be rounded off to 6.10
and if it is 6.115
then it will be rounded off to 6.12
as 5
is the mid point
.
If the MidpointRounding.AwayFromZero
is used as shown below
decimal number = 6.1056M;
Console.WriteLine (Math.Round(number,2, MidpointRounding.AwayFromZero));
那么上述值将分别四舍五入为6.11
和6.12
,即始终为数字away from zero
,即将采用next higher number
.
then the above values will be rounded off to 6.11
and 6.12
respectively, i.e. always the number away from zero
, in other words the next higher number
will be taken.
这篇关于格式化十进制变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!