如何从C#中的数字中删除小数部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13062481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove decimal part from a number in C#
提问by Divya
I have number of type double. double a = 12.00 I have to make it as 12 by removing .00
我有双倍类型的数量。double a = 12.00 我必须通过删除 .00 使其成为 12
Please help me
请帮我
回答by Adil
回答by Jon Skeet
Well 12and 12.00have exactly the same representation as doublevalues. Are you trying to end up with a doubleor something else? (For example, you could cast to int, if you were convinced the value would be in the right range, and if the truncation effect is what you want.)
好吧,12并且12.00具有与double值完全相同的表示形式。你是想以 adouble或其他东西结束吗?(例如,int如果您确信该值在正确的范围内,并且截断效果是您想要的,则您可以强制转换为 。)
You might want to look at these methods too:
您可能还想查看这些方法:
Math.FloorMath.CeilingMath.Round(with variations for how to handle midpoints)Math.Truncate
Math.FloorMath.CeilingMath.Round(关于如何处理中点的变化)Math.Truncate
回答by Habib
If you just need the integer part of the double then use explicit cast to int.
如果您只需要 double 的整数部分,则使用显式转换为 int。
int number = (int) a;
You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.
您可以使用Convert.ToInt32 Method (Double),但这会将数字四舍五入到最接近的整数。
value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
值,四舍五入到最接近的 32 位有符号整数。如果 value 介于两个整数之间,则返回偶数;即4.5转4,5.5转6。
回答by Faiyaz
Use Decimal.Truncate
It removes the fractional part from the decimal.
它从小数中删除小数部分。
int i = (int)Decimal.Truncate(12.66m)
回答by ????? ???
here is a trick
这是一个技巧
a = double.Parse(a.ToString().Split(',')[0])
回答by vohrahul
Reading all the comments by you, I think you are just trying to display it in a certain format rather than changing the value / casting it to int.
阅读您的所有评论,我认为您只是想以某种格式显示它,而不是更改值/将其转换为int.
I think the easiest way to display 12.00as "12"would be using string format specifiers.
我认为,以显示最简单的方法12.00是"12"将使用字符串格式说明。
double val = 12.00;
string displayed_value = val.ToString("N0"); // Output will be "12"
The best part about this solution is, that it will change 1200.00to "1,200"(add a comma to it) which is very useful to display amount/money/price of something.
这个解决方案最好的部分是,它会更改1200.00为"1,200"(在其中添加一个逗号),这对于显示某物的金额/金钱/价格非常有用。
More information can be found here: https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
更多信息可以在这里找到:https: //msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
回答by RainyTears
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
因为点之后的数字只是零,最好的解决方案是使用 Math.Round(MyNumber)

