Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currency formatting in .NET gives white space between amount and currency

I'm having issues with currency formatting in C#. I'm using framework 2.0.

When I use this code:

CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";

price.Value.ToString("C", numberFormatInfo) seems to give me a string with a white space between amount and currency. That's horrible! I absolutely need a no-break space! What is going on? Am I missing a format property or is it the C# standard?

Thanks for your help!

So basically you want price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');? At least that should be the code for non breaking space. – Corak

Exactly the same as above commentor, but using the asci-values instead; > price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160); (160 is a lot > easier to remember, atleast for me :)) – flindeberg

like image 745
user1835565 Avatar asked Sep 11 '13 14:09

user1835565


1 Answers

Adding an answer based on my interpretation of the question, which @Corak seems to share.

// Convert "breaking" spaces into "non-breaking" spaces (ie the html  )
price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160);

Doing the same with unicode (courtesy of @Corak's link):

// Convert "breaking" spaces into "non-breaking" spaces without int cast to char
price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');

And btw (roslyn repl):

> '\u00A0' == (char) 160
true

And if you are going to be using it alot also get the extension method:

public static class StringExtensions 
{// CurrencyType is your currency type, guessing double or decimal?
 public static string ToCurrencyString(this CurrencyType value, IFormatInfo format)
 {
    return value.ToString("C", format).Replace((char) 32, (char) 160);
 }
}
like image 170
flindeberg Avatar answered Sep 22 '22 19:09

flindeberg