C# 将十进制变量拆分为整数部分和分数部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10702199/
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
Split decimal variable into integral and fraction parts
提问by invarbrass
I am trying to extract the integral and fractional parts from a decimal value (both parts should be integers):
我试图从十进制值中提取整数和小数部分(两个部分都应该是整数):
decimal decimalValue = 12.34m;
int integral = (int) decimal.Truncate(decimalValue);
int fraction = (int) ((decimalValue - decimal.Truncate(decimalValue)) * 100);
(for my purpose, decimal variables will contain up to 2 decimal places)
(出于我的目的,十进制变量将包含最多 2 个小数位)
Are there any better ways to achieve this?
有没有更好的方法来实现这一目标?
回答by Barry Kaye
How about:
怎么样:
int fraction = (int) ((decimalValue - integral) * 100);
回答by SOReader
Try mathematical definition:
尝试数学定义:
var fraction = (int)(100.0m * (decimalValue - Math.Floor(decimalValue)));
Although, it is not better performance-wise but at least it works for negative numbers.
虽然,它在性能方面并不是更好,但至少它适用于负数。
回答by Girish Sakhare
decimal fraction = (decimal)2.78;
int iPart = (int)fraction;
decimal dPart = fraction % 1.0m;
回答by OMARY
decimal fraction = doubleNumber - Math.Floor(doubleNumber)
or something like that.
或类似的东西。
回答by Aamol
For taking out fraction you can use this solution:
要取出分数,您可以使用此解决方案:
Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)

