Search code examples
c#doublenumber-formattingglobalizationtryparse

How to prevent converting of double with high value?


I have got a function which checks if a string is a double and if so the value has to be rounded to two digits and returned as string. If not an empty string will be returned. This works fine for the most cases. But for the upper border, the value is rounded to the next integer which is wrong. How can I force that the value will not be rounded?

Upper border: 9999999999999999.9900000000000000

Expected value: 9999999999999999.99

Given value: 10000000000000000

public string MyConvertFunction(string param)
{ 
    double result;

    if(System.Double.TryParse(param, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.GetCultureInfo("en-US"), out result)) {
        if(result == 0.0) return "";
        return result.ToString("0.00", System.Globalization.CultureInfo.GetCultureInfo("en-US"));
    }

    return "";
}

It seems that the rounding is at the TryParse part. Therefore something like this

double x = Math.Truncate(myDoubleValue * 100) / 100;

Not possible.


Solution

  • A double can hold about 15 to 16 significant digits, and your huge number is larger than that, so that's why your value gets rounded. So, there is no solution to your problem. You have two options:

    1. Live with the fact that you cannot represent so large numbers without loss of precision. As you keep adding digits to the left end of the number, some digits on the right end of the number will not be meaningful anymore.

    2. Stop using double and start using decimal instead. This data type performs worse than double, but it has a much greater precision.

    Reference for decimal: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/decimal