CSharp: How to format a double value according to culture-specific formatting in Unity C#
Numbers are formatted differently in various cultures (locale). Every locale follows different standards.
For simplicity, let us consider how decimals and thousands are separated in two cultures (locales).
- en-US (US English) 🇺🇸
- de-DE (DE Deutsch) 🇩🇪
Decimal separator
- In “en-US” period (.) is used to separate the decimals.
- For example, $100.00 or 10.00
- In “de-DE” comma (,) is used to separate the decimals.
For example, 100,00€ or 10,00
Thousands separator
- In “en-US” comma (,) is used to separate the thousands.
- For example, $1,000.00 or 1,000.00
- In “de-DE” period (.) is used to separate the thousands.
For example, 1.000,00€ or 1.000,00
To learn more, refer to Number formatting documentation.
If you are developing applications in Unity using C#. You would like to format according to different cultures. Here is how you can format double data type according to locale using C# in Unity project,
using System.Collections.Generic;
using System.Globalization;
public class ExampleFormatDoubleValues : MonoBehaviour
{
double inputValueDouble = 79.00;
string outputValueDoubleString = string.Format(CultureInfo.InvariantCulture, "{0}", inputValueDouble);
// Output according to different cultures
// if culture is en-US then output is 79.00
// if culture is de-DE then output is 79,00
}
In the above code example,
- the value
79.00
is stored ininputValueDouble
. - It is converted using the method String.Format Method —
Format(IFormatProvider, String, Object[])
- The
IFormatPorvider
isCultureInfo.InvariantCulture
- The
string
is"{0}
- The
Object[]
isinputValueDouble
- The converted value is stored in
outputValueDoubleString
To learn more, refer to System.Collections.Generic Namespace and CultureInfo Class.
I hope my article helps you understand how to work with string format for formatting different data types in Unity using C#.
If you like my articles, please follow me. You can also support me by https://www.buymeacoffee.com/akarshseggemu