Globalized custom number formatting - Variable decimal points - c#

I'm trying to alter the existing number formatting in my company's application to make it more readable for international users. This is a stock trading application, so most stock prices come in with numbers precise to 2 decimal points, like so-> 17.23 We could also get ticks in that have precision out to 4 decimal points, so a penny stock might be 0.0341. The original string format that we were using for stocks was "#,##0.00##" Which would give us the format we wanted (essentially trimming '0's). The problem here is the ',' and '.' are forced onto the user, where in many other countries the thousands separator is '.' and the decimal point is ','. Boss man doesn't want to use "N4" for all numbers, even though this would resolve the globalization issue. Is it possible to have a globalized custom string format?
Other options besides writing some middle man code to internationalize numbers formatted the original way or another string.format method?

Check this out:
float value = 0.0341f;
string output = string.Empty;
CultureInfo brazil = new CultureInfo("pt-BR");
CultureInfo usa = new CultureInfo("en-US");
output = value.ToString("C4", brazil.NumberFormat); //output is R$ 0,0341
output = value.ToString("C4", usa.NumberFormat); //output is $0.0341

The , and . in the custom format string already translate into the correct separators for the current culture. You should not need to change your code. See MSDN.

Related

C# ToString("C") converting the decimal to currency value pound instead of dollar

I am converting a double value to currency string format and it gets converted string with pound symbol currency. Is it culture dependent?
If you always want to use a a specific locale, which may be desirable if your server target is hosted in a different timezone, etc... ToString() can be supplied with a CultureInfo argument.
How to convert string to double with proper cultureinfo
If you want to tailor it to the user's locale, You might be able to examine the request values:
Get CultureInfo from current visitor and setting resources based on that?
This probably isn't the best/most efficient way to do this, but have the decimal you want to show pounds converted into a string and just replace the dollar sign with the pound sign
decimal monies = 2.50m;
string moniesString = monies.ToString();
string moniesFormatted = string.Format("{0}£", moniesString);
again this most likely isn't the best or most efficient way to do so, but its a work around to avoid having to change your computer settings.
Hope this helps! If not let me know and I'll remove the answer(I had to use an answer because I can't comment under 50 rep, otherwise I would have used a comment to get some more clarity before answering) Cheers!
Control Panel > Region > Formats > Advanced

String.Format in conjunction with CultureInfo C#

I want to format a price using string.Format. I am able to get the correct currency symbol but can't figure out the regex to always have 2 decimal places regardless if they are 0s. Here is my code:
CultureInfo us = CultureInfo.GetCultureInfo("en-US");
price.text = string.Format(us, "{0:C}",inventory.priceTotal);
Add 2 to C so C2
string.Format(us, "{0:C2}",inventory.priceTotal);
See also Standard Numeric Format Strings
Think my inventory code is a mess. I have strings being parsed to doubles and then passing those to the .text via .ToString(). I think I will separate the digits from the symbol and just dynamically set the symbol independently.

String.Format an integer to use a thousands separator with decimal value in danish culture

I have a string totalPRice which holds a value like this 1147,5
I want two things.
1)round the value so that there is always two digits after ,
2)Implement thousands separator in this string, So that final out put will be some thing like this 1.147,50
I have tried some thing like this
String.Format("{0:0.00}", totalPRice)
It does my first requirement correctly by producing an output 1147,50.
But I am way behind in my second requirement. Can any one tell me how I can achieve this?
Note: In danish culture . stands for , and , stands for .
You can refer to Standard Numeric Format Strings and use
string.Format("{0:N2}", 1234.56)
You may also specify the culture manually, if danish is not your default culture:
var danishCulture = CultureInfo.CreateSpecificCulture("da-DK");
string.Format(danishCulture, "{0:N2}", 1234.56);
see MSDN Reference for CultureInfo
You should create a culture-specific CultureInfo object and use it when converting the number into a string. Also, you can set the default culture for your whole program.
Then, your code will look like this:
// create Dennmark-specific culture settings
CultureInfo danishCulture = new CultureInfo("da");
// format the number so that correct Danish decimal and group separators are used
decimal totalPrice = 1234.5m;
Console.WriteLine(totalPrice.ToString("#,###.##", danishCulture));
Note that . and , in the formatting string are specified opposit as you want. This is because they identify decimal and group separators, and are replaced with the correct culture specific-ones.
Try this:
String.Format("{0:N2}", totalPRice)
Another possibility is to use the ToString(string format) overload.
totalPRice.ToString("N2");
If this is a currency value (money!), then it's better to use the current format specifier 'C' or 'c':
string.Format("{0:C}", 1234.56)
Normally I don't write the number of decimal digits since it comes from the international configuration.
You may way to use a different colture specifier if you don't want to use the default one.
var colture = CultureInfo.CreateSpecificCulture("§§§§§");
string.Format(culture, "{0:C}", 1234.56);
where §§§§§ is the string that identifies the desired colture.
Try this for Price format. Put it under template field instead of BoundField.
<%#(decimal.Parse(Eval("YourDataField").ToString())).ToString("N2")%>

Converting string to decimal: how to handle the decimal separator in different cultures

I need to write decimal value to ms access database, but i have a problem with conversion values to decimal in different cultures. Have a values from file, which separates by commma. I try:
public decimal CSingleCulture (string str)
{
string sep = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
string s = str.Replace(",", sep);
return decimal.Parse(s);
}
if NumberDecimalSeparator = "." then work is good, but if NumberDecimalSeparator = "," problems begin... decimal.Parse(s) always return vlaues separates by dot. In this situation, when inserted into a database error occurs.
The recommended way to deal with this is to store the value as a number rather than a string. Both in the database and in your program. When you do that, your current problem simply never arises.
The only time you deal with numbers in string format is when you display them, or accept user input. In those scenarios you can use the user's culture settings to let them see and use their preferred separator.
Should you ever need to convert between string and number for persistence then you must use culture invariant conversion. This appears to be where you are falling down. I suspect that the file you read has no well-defined format. Make sure that when you read and write the file you use CultureInfo.InvariantCulture. If the file does have a well-defined format that differs from the invariant culture, then use an appropriate specific CultureInfo.
Can't actually understand what is it you're trying to accomplish, and I have to agree with the other answer. But one other thing that's good to know is you can use invariant culture like so:
double.Parse("15.0", CultureInfo.InvariantCulture)
This will always expect dot character to delimit your decimal digits regardless of what is set in current thread's culture.

Language invariant Double.ToString()

I am passing a double across a network,
currently I do
double value = 0.25;
string networkMsg = "command " + value;
the networkMsg is fine in english where its 0.25 and french where its 0,25, but when i go from a french computer to an english computer one side is making it 0.25 and the other is trying to read 0,25.
So i can to use region invariant methods in my code.
I have found Val(networkMsg) that will always read 0.25 no matter the region.
but I cannot find a guaranteed way of converting from value to 0.25 region invariant.
would value.toString("0.0") work?
Use:
string networkMsg = "command " + value.ToString(CultureInfo.InvariantCulture);
or:
string networkMsg = string.Format(CultureInfo.InvariantCulture, "command {0}", value);
This needs using System.Globalization; in the top of your file.
Note: If you need full precision, so that you can restore the exact double again, use the Format solution with the roundtrip format {0:R}, instead of just {0}. You can use other format strings, for example {0:N4} will insert thousands separators and round to four dicimals (four digits after the decimal point).
Since C# 6.0 (2015), you can now use:
string networkMsg = FormattableString.Invariant($"command {value}");
The . in the format specifier "0.0" doesn't actually mean "dot" - it means "decimal separator" - which is , in France and several other European cultures. You probably want:
value.ToString(CultureInfo.InvariantCulture)
or
value.ToString("0.0", CultureInfo.InvariantCulture)
For info, you can see this (and many other things) by inspecting the fr culture:
var decimalSeparator = CultureInfo.GetCultureInfo("fr")
.NumberFormat.NumberDecimalSeparator;
Specify the invariant culture as the format provider:
value.ToString(CultureInfo.InvariantCulture);

Categories