如何使用math.round()方法和变量 [英] How to use math.round() method with variable
问题描述
Hello All
我正在使用带有c#变量的Math.Round()方法。
ie
Math.Round()带变量的方法
十进制trm2 = 22.9866;
trm2 =数学.Round(trm2,2);
然后输出是22.98(罚款确定)
但是当
十进制trm2 = 22.00;
trm2 = Math.Round(trm2,2);
然后输出是22.00
但是我想要22(没有零)
怎么样?
plz help
我尝试过:
Hello All
我正在使用带有c#变量的Math.Round()方法。
ie
Math.Round()带变量的方法
十进制trm2 = 22.9866;
trm2 = Math.Round(trm2,2);
然后输出是22.98(罚款确定)
但是当
十进制trm2 = 22.00;
trm2 = Math.Round(trm2,2);
然后输出是22.00
但是我想要22(没有零)
怎么样?
plz help
Hello All
A am using Math.Round() Method with variable in c#.
i.e
Math.Round() Method with variable
decimal trm2 = 22.9866;
trm2 = Math.Round(trm2, 2);
then output is 22.98 (fine ok)
but when
decimal trm2 = 22.00;
trm2 = Math.Round(trm2, 2);
then output is 22.00
but i want 22 (without zero)
HOW ?
plz help
What I have tried:
Hello All
A am using Math.Round() Method with variable in c#.
i.e
Math.Round() Method with variable
decimal trm2 = 22.9866;
trm2 = Math.Round(trm2, 2);
then output is 22.98 (fine ok)
but when
decimal trm2 = 22.00;
trm2 = Math.Round(trm2, 2);
then output is 22.00
but i want 22 (without zero)
HOW ?
plz help
推荐答案
小数值总是有小数点右边的数字,除非你明确告诉它不是当你将它转换为字符串以呈现给用户时。
你不能告诉小数(或浮点数或双倍)值你没有任何东西可以告诉我们小数点右边因为它们没有任何格式化概念 - 它们只是数字!
如果你不想让数字显示小数部分,那么在转换它时指定它通过为其指定格式#0:
A decimal value always has "digits to the right of the decimal point" unless you specifically tell it not to when you convert it to a string for presentation to the user.
You can't tell a decimal (or a float, or a double) value "you don't have anything to teh right of the decimal point" because they don't have any concept of formatting - they are just numbers!
If you don't want numbers to show the fractional part, then specify it when you convert it by specifying a format "#0" for it:
decimal d1 = 22.00M;
Console.WriteLine("{0}:{1} - {2:0#}", d1, d1.ToString("#0"), d1);/pre>
<pre lang="text">22.00:22 - 22
请注意,这也将围绕22.9866:
Do note that that will round 22.9866 as well:
decimal d1 = 22.9866M;
Console.WriteLine("{0}:{1} - {2:0#}", d1, d1.ToString("#0"), d1);
22.9866:23 - 23
试试这个
try this
int decimalPlace = (trm2 % 1) == 0 ? 0 : 2;
trm2 = Math.Round(trm2, decimalPlace);
这篇关于如何使用math.round()方法和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!