C#对于Decimal而言值太大的解决方法

问题描述 投票:0回答:2

我有一个功能非常适合不太大的值:

    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

但是如下所示:12345678901234567890.12345678901234567890m。当然因为12345678901234567890.12345678901234567890m * Math.Pow(10,20)对于小数来说太大了,但我不需要这个十进制我需要这个像BigInteger之前的例子一样

12345678901234567890.12345678901234567890m = 1234567890123456789012345678901234567890

买,我不知道什么/如何解决这个问题的最佳方法...

c# decimal biginteger
2个回答
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);
    }

© www.soinside.com 2019 - 2024. All rights reserved.