我有一个函数,对于不太大的值,效果很好:
public BigInteger GetFrom(decimal value)
{
var decimalPlaces = 20;
var factor = (decimal) Math.Pow(10, decimalPlaces);
return new BigInteger(value * factor);
}
它可以正确转换:
123m = 12300000000000000000000
123.123456789m = 12312345678900000000000
0.123m = 12300000000000000000
0.123456789m = 12345678900000000000
0.123456789012345678902345678901234567890m = 12345678901234567890
1.123456789012345678902345678901234567890m = 112345678901234567890
但是会发出类似这样的消息:12345678901234567897890.12345678901234567890m。 当然,因为12345678901234567890.12345678901234567890m * Math.Pow(10,20)对于小数来说太大了,但是我不需要像十进制那样将它作为小数,我需要像以前的例子一样将其作为BigInteger
12345678901234567890.12345678901234567890m = 1234567890123456789012345678901234567890
购买,我不确定解决此问题的最佳方法是什么/如何...
答案 0 :(得分:0)
好吧,基本上遵循jdweng的建议:
public BigInteger GetFrom(decimal value)
{
DecimalPlaces = 20;
string strValue = HasDecimalPlaces(value) ? ConvertAValueWithDecimalPlaces(value) : ConvertARoundedValue(value);
return BigInteger.Parse(strValue);
}
private static bool HasDecimalPlaces(decimal value)
{
return ! Math.Round(value).Equals(value) || value.ToString(CultureInfo.InvariantCulture).Contains(".");
}
private string ConvertAValueWithDecimalPlaces(decimal value)
{
var commaLeftRight = value.ToString(CultureInfo.InvariantCulture).Split('.');
return commaLeftRight[0] + commaLeftRight[1].PadRight(DecimalPlaces, '0').Substring(0, DecimalPlaces);
}
private string ConvertARoundedValue(decimal value)
{
return value.ToString(CultureInfo.InvariantCulture) + new string('0', DecimalPlaces);
}
答案 1 :(得分:-1)