带小数位的 BigInteger 字符串表示形式
我试图创建一个大整数除以某物时的十进制表示形式。下面是执行此操作的代码,基本上我希望精度为 2 位。
public string GetDecimal(BigInteger bigInteger,int divisor)
{
var remainder = BigInteger.Remainder(bigInteger, divisor);
var dividend = BigInteger.Divide(bigInteger, divisor);
var d = ((double)remainder / divisor);
var decimalPart = Math.Round(d, 2);
var retValue = dividend + decimalPart.ToString(".00");
return retValue;
}
}
请问有更好的方法吗?
谢谢, -麦克风
I'm trying to create a decimal representation of a big integer when it's divided by something. The follwoing is the code which does it, basically I want the precision to be of 2 places.
public string GetDecimal(BigInteger bigInteger,int divisor)
{
var remainder = BigInteger.Remainder(bigInteger, divisor);
var dividend = BigInteger.Divide(bigInteger, divisor);
var d = ((double)remainder / divisor);
var decimalPart = Math.Round(d, 2);
var retValue = dividend + decimalPart.ToString(".00");
return retValue;
}
}
Is there a better way of doing this please?
Thanks,
-Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能不应该自行转换类型并进行长除法。这应该适用于任何 BigInteger 值。
我确信这里还有改进的空间......
You should probably not convert the types and do the long division on your own. This should work with any BigInteger value.
I'm sure there's room for improvement here...
内置的 .net
decimal
类型为 128 位,可与其他类型的类似舍入结构配合使用。这个数字还不够大吗?The built in .net
decimal
type is 128bit, and works with similar rounding constructs of other types. Is this number not large enough?而不是对其进行数学运算,特别是使用不太精确的类型(例如 double)。
只需构建一个包含除最后两位数字之外的所有数字的字符串,附加一个小数点,然后放入最后一个数字。
例如
Instead of doing maths on it especially using less accurate types like double.
simply build a string with all but the last two digits, append a decimal point and then put the last one in.
e.g. Something like
此代码仅适用于正值,并使用
AwayFromZero
中点舍入。我也不关心本地化问题。This code only works for positive values, and uses
AwayFromZero
midpoint rounding. I also didn't care about localization issues.