CSharp: How to format a double value according to culture-specific formatting in Unity C#

Akarsh Seggemu
2 min readMar 17, 2022

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 in inputValueDouble.
  • It is converted using the method String.Format MethodFormat(IFormatProvider, String, Object[])
  • The IFormatPorvider is CultureInfo.InvariantCulture
  • The string is "{0}
  • The Object[] is inputValueDouble
  • 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

--

--

Akarsh Seggemu

IT Team Lead | MSc in Computer Science from Technische Universität Berlin | Writing articles to Empower Software Engineers and IT Leaders