Search code examples
vb.netglobalizationcultureinfoculture

VB.NET Formatting numbers according culture selected


I have a multilanguage vb.net app.

I am trying to format a number (ULong) to display it according to current language currency group separator by doing this:

value.ToString("0.##", CultureInfo.CurrentCulture)

CultrueInfo.CurrentCulture can be english (en-GB), spanish (es-ES) or catalan (ca-ES) depending on the language selected in the app.

The problem is the following:

  1. If spanish (es-ES) is selected then value is not correctly formatted as spanish language currency group separator is ',' instead of '.' indicated in "0.##" so I need to put "0,##" instead.

for example 1200 is formated as is 1200 instead of 1.200

  1. But if I change mask to "0,##" then if language is set to en-GB, value is not formatted correctly as currency group separator for it is "." instead of "," indicated in "0,##" so I need to put "0.##" instead.

So how to adapt mask automatically to work for all languages? detecting language and set the correct mask accordingly? but it is ok for a few language but not suitable for a lot of languages...


Solution

  • The problem is you're hardcoding the radix point (, or . character).

    Use a Standard Formatting String instead. See here: https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

    N - Number - Integral and decimal digits, group separators, and a decimal separator with optional negative sign.

    The N{n} format uses "Number" formatting and an integer following that is the number of places after the radix point:

    value.ToString("N2", CultureInfo.CurrentCulture)