Search code examples
c#globalization

C# - Using NumberFormatInfo with Convert.ToDouble to return double


In my application I have internationalization and so we have a bunch of methods to deal with formatting. One of them should receive a double and format it to two decimal places and return a double. For doing so, we are using NumberFormatInfo according to the culture selected.

The problem is I cant get Convert.ToDouble to work with NumberFormatInfo the way I would like to. Basically what I want to know is why this:

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var myDouble = 9.983743;

        var nfi = new NumberFormatInfo() {
            NumberDecimalDigits = 2
        };

        Console.WriteLine("Original value: " + myDouble);
        Console.WriteLine("Converted value: " + Convert.ToDouble(myDouble, nfi));
    }
}

Prints

Original value: 9.983743
Converted value: 9.983743 // Should be 9.98

And how can I get the result I want using NumberFormatInfo only, if possible.

Thanks,


Solution

  • From MSDN:

    The NumberDecimalDigits property is used with the "F" and "N" standard format strings without a precision specifier in numeric formatting operations.

    The default is the generic formatting (G). So this will give you the desired result:

    Console.WriteLine(myDouble.ToString("N", nfi));
    

    However, 2 is the default value anyway. And it is better to specify it explicitly:

    Console.WriteLine(myDouble.ToString("N2", NumberFormatInfo.InvariantInfo));
    

    Update:

    Yeah but I do need to return a double from my method.

    Now I see. In your place I would return the original double in that case, too. If the consumer of your API wants to display/store it as a string with two digits, then it is his responsibility to format it.

    If you really want to omit the last digits of the precision and return a modified value, then use Math.Round instead (but I would not recommend that).