开发者

Decimal parse of exponential 0 value (0+E3)

开发者 https://www.devze.com 2023-03-01 19:21 出处:网络
Our middle tier sends us serialized objects and sometimes a 0, due to some math operations in java on the server, come through as 0E+3. When deserializing the object we get an XmlException --> 开发者_

Our middle tier sends us serialized objects and sometimes a 0, due to some math operations in java on the server, come through as 0E+3. When deserializing the object we get an XmlException --> 开发者_JAVA百科System.OverflowException because the value is too large or small for a decimal.

Why can't decimal.Parse handle this conversion?

Is there a way to protect our client from these numbers coming in this way?


You could try:

decimal.Parse(numberText, System.Globalization.NumberStyles.Any)

EDIT:

This doesn't work for 0E+3 unfortunately

Works:

Console.WriteLine(decimal.Parse("0", System.Globalization.NumberStyles.Any));
Console.WriteLine(decimal.Parse("123.45", System.Globalization.NumberStyles.Any));
Console.WriteLine(decimal.Parse("1.35E+6", System.Globalization.NumberStyles.Any));
Console.WriteLine(decimal.Parse("1.54E-5", System.Globalization.NumberStyles.Any));

Doesn't work:

Console.WriteLine(decimal.Parse("0E+3", System.Globalization.NumberStyles.Any));

Is the problem number always 0E+3?

If so, you could write a helper method to handle this:

decimal ParseDecimal(string number)
{
    if (number.Equals("0E+3", StringComparison.OrdinalIgnoreCase))
    {
        return 0;
    }

    return decimal.Parse(number, System.Globalization.NumberStyles.Any);
}


Java is probably doing this calculation as a double (which means you also don't need the extra precision of a Decimal) if they come out this way... consider using double instead of decimal.

If you have to, just trim out the E[+-]?([0-9]+)$ manually with a regex and do the multiplication yourself. Or match ^0E as a special case (it seems NumberStyles.Any can't handle it) and just return 0.


Change it to a float or double and it will parse it correctly. Although be careful, the precision will be much lower (7 digits for float or 15-16 digits for double vs 28-29 for decimal).

0

精彩评论

暂无评论...
验证码 换一张
取 消