Search code examples
c#unity-game-engineformattostringseparator

c# How to separate an int with decimal points?


I am trying to format an int with decimal points as separators, not commas.

Example: 1234567890 should be formatted to 1.234.567.890

text_team1.text = em.team1Score.ToString("#,##0");

This will give 1,234,567,890

However in this topic there was some information about using the class CultureInfo which contains the format-style, so I used several of them:

text_team1.text = em.team1Score.ToString("#,##0", new System.Globalization.CultureInfo("IS-is"));

as an example. But it seems that every cultureInfo uses a comma as separator.

Even by editing the string afterwards, there is still the comma as seperator.

text_team1.text = em.team1Score.ToString("#,##0");
text_team1.text.Replace(',','.');

Solution

  • Even by editing the string afterwards, there is still the comma as seperator.

    text_team1.text = em.team1Score.ToString("#,##0");
    text_team1.text.Replace(',','.');
    

    You forgot to assign the replaced string back.

    text_team1.text = text_team1.text.Replace(',','.');
    

    EDIT:

    If you still prefer a solution without using the Replace function, you can use the Extension method below. It works for strings and ints. Please Google and read about extension methods if you don't know how they work.

    Create and place the ExtensionMethod script in any folder in your project:

    using System.Globalization;
    using System;
    
    public static class ExtensionMethod
    {
        public static string formatStringWithDot(this string stringToFormat)
        {
            string convertResult = "";
            int tempInt;
            if (Int32.TryParse(stringToFormat, out tempInt))
            {
                convertResult = tempInt.ToString("N0", new NumberFormatInfo()
                {
                    NumberGroupSizes = new[] { 3 },
                    NumberGroupSeparator = "."
                });
            }
            return convertResult;
        }
    
        public static string formatStringWithDot(this int intToFormat)
        {
            string convertResult = "";
    
            convertResult = intToFormat.ToString("N0", new NumberFormatInfo()
            {
                NumberGroupSizes = new[] { 3 },
                NumberGroupSeparator = "."
            });
            return convertResult;
        }
    }
    

    Usage:

    string stringToFormat = "1234567890";
    Debug.Log(stringToFormat.formatStringWithDot());
    

    Or

    int intToFormat = 1234567890;
    Debug.Log(intToFormat.formatStringWithDot());
    

    Or

    string stringToFormat = "1234567890";
    text_team1.text = stringToFormat.formatStringWithDot();
    

    Use each one depending on which scenario you run into.