How would I separate thousands with space in C#
Asked Answered
N

7

55

Assume I have the following decimal number that I have to format so that every thousand should be separated with a space:

 897.11 to 897.11
 1897.11 to 1 897.11
 12897.11 to 12 897.11
 123897.11 to 123 897.11

I have tried Decimal.ToString("0 000.00"). Although this works pretty well when the number is 1897.11. But when it's 897.11 I get 0 897.11.

Neman answered 8/7, 2013 at 13:25 Comment(0)
S
97

Pass in a custom NumberFormatInfo with a custom NumberGroupSeparator property, and use the #,# format to tell it to do number groups. This example uses the invariant culture's number format as its basis.

var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberGroupSeparator = " ";
string formatted = 1234897.11m.ToString("#,0.00", nfi); // "1 234 897.11"
Sweeten answered 8/7, 2013 at 13:32 Comment(1)
+1 , I have edited this answer to handle zero values properly - the previous format string "#,#.00" caused zero to be represented as ".00" now it is "0.00"Footcloth
R
23

You need a custom number format provider where you change the character yourself:

    static void Main(string[] args)
    {
        decimal d = 2000000;

        var f = new NumberFormatInfo {NumberGroupSeparator = " "};

        var s = d.ToString("n", f); // 2 000 000.00
    }

Here I also specify to format it as a number (using "n"), please see this link for other formatting options:

Standard Numeric Format Strings

In this case, it won't work if you format as a currency or a percentage, because as you may already note the NumberFormatInfo has separate properties for those.

The current culture format info can be found on System.Globalization.CultureInfo.CurrentCulture.NumberFormat.

Recommend answered 8/7, 2013 at 13:35 Comment(0)
E
14

try this

int testNumber = 134566548;
Console.WriteLine(string.Format("{0:N}", testNumber));

You will received : 134 566 548,00

Don't forget your culture.

Expansile answered 8/7, 2013 at 13:32 Comment(0)
T
11

with a custom format string, but use '#' not '0's a 0 is a mandatory token it will be there no matter how long the number is, the pound sign (#) is optional token, it will only be used for digits actually in the number.

  Decimal.ToString("# ###.00")  

NOTE. I'll leave this here, but @Tim S' answer is a better one.

When I try this I see it only generates the first separator... I guess the separator only works for commas and periods here. As a workaround (up to the maximum size number you expect), try this instead.

  Decimal.ToString("# ### ### ### ###.00")  
Thuythuya answered 8/7, 2013 at 13:27 Comment(5)
For 1234897.11 this results in 1234 897.11 (i.e. it only separates the first group).Sweeten
@Tim, that sounds like a bug in the framework code. see my editThuythuya
@Tin S answer is better than mine. Did not know NumberFormatInfo existedThuythuya
I feel like this one is more obvious at a glance what it is doing.Bashan
for 0.1 it returns ".1". For fix it try Decimal.ToString("# ##0.00") and you may need .Trim()Annisannissa
P
5

Sweden Use thousand separator as Space(" ") and Decimal point separator as Comma(,). We can achieve this in the following way.

decimal myNumbber = 5878.476M;
var swedishCulture = new CultureInfo("sv-SE");           
swedishCulture.NumberFormat.NumberDecimalSeparator = ",";
swedishCulture.NumberFormat.NumberGroupSeparator = " ";
var s = myNumbber.ToString("#,###.00", swedishCulture);

Which gives the output

"5 878,48"
Poi answered 21/1, 2020 at 5:42 Comment(1)
Question, why would you need to specify the separator values? Aren't these already defined in the CultureInfo's NumberFormatInfo property?Elliot
B
4

Norwegian locale uses spaces as a separator, so if you were designing a website or application specifically for Norwegians, then you could use:

(123897.11).ToString("n",new CultureInfo("nb-NO"))

Which results in

"123 897,11"

Obviously, if you're not writing an application for the Norwegian market, then this would be a silly solution.

Bern answered 20/9, 2016 at 15:55 Comment(1)
I used something like (123897.11).ToString("n4",new CultureInfo("nb-NO")) for 4 decimal places. Tks.Scute
D
0
double salaire = 0;
string salaire_s = "0";

private void txtSalaire_TextChanged(object sender, EventArgs e)
{
    txtSalaire.Text = FormatMontant(salaire_s);
    txtSalaire.Select(txtSalaire.Text.Length, 0);
}

private void txtSalaire_KeyPress(object sender, KeyPressEventArgs e)
{
    salaire = ClassUtility.AllowNumbersFormatDecimal(e, salaire_s);
    salaire_s = salaire.ToString();
}

public static string FormatMontant(string montant_string)
{
    double montant = 0;
    if (montant_string.Equals(""))
    {
        montant_string = "0";
    }
    montant = Convert.ToDouble(montant_string);
    return String.Format("{0:n0}", montant);
}
Distance answered 18/5, 2023 at 14:39 Comment(1)
Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?Laurilaurianne

© 2022 - 2024 — McMap. All rights reserved.