String.Format in conjunction with CultureInfo C# - 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.

Related

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")%>

How do I make sure a decimal is always displayed as xxxx.xxxx positive and negative?

I have a decimal on an object in C#. I want to be able to display it as xxxx.xxxx at the moment the value is -1.61769, basically I want to round the last two digits up and make sure that it only ever has 4 decimal places after the decimal place. Im not sure if this is a Math operation (i.e. Math.Round) or is a validation operation (i.e. string.Format) or both?..
Hope someone can help...
Try this:
string result = d.ToString("0.0000");
You may also want to specify a culture:
CultureInfo cultureInfo = CultureInfo.InvariantCulture;
string result = d.ToString("0.0000", cultureInfo);
Result:
-1.6177
See it working online: ideone
That depends on whether you want at most four decimal places, or exacty four decimal places.
If you round the value, you get at most four decimal places:
value = Math.Round(value, 4);
The value 1.61799 for example would be rounded to 1.6180 and display as 1.618.
If you format the value, you get exactly four decimal places:
string formatted = value.ToString("0.0000");
you have to check with string.Format if you are looking to have a string.
check that link c# double format
if you are looking for keeping the value of the number you should use Math.round
Did you try Math.Abs()?
According to this MSDN-Page it is not possible.
Because it would display a diffierent Value.
Math.Abs(-1.61769).ToString("####.####");

How can I display culture-specific native digits instead of Arabic numerals?

I want to convert a numeric value to a string, displaying culture-specific digits. For example, the Dari language used in Afghanistan (culture name "prs-AF") uses Eastern-Arabic numerals instead of the Arabic numerals used in most Western cultures (0,1,2,3,4,5,6,7,8,9).
When examining the CultureInfo class built into the Framework, it lists the correct native digits (screenshot taken from output in LinqPad):
CultureInfo.CreateSpecificCulture("prs-AF").NumberFormat.NativeDigits
However, when trying to convert a number to a string to display in that culture, I am not getting the native digits:
var number = 123.5;
var culture = CultureInfo.CreateSpecificCulture("prs-AF");
Thread.CurrentThread.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
var text = number.ToString(culture);
Console.WriteLine(text);
Can anyone tell me how to display the native digits?
Digit substitution is something that takes place when you display text that contain digits.
It is not supposed to change the string representation of a number, as you've seen.
The number 123.5 is formatted as the string 123.5 no matter digit substitution. It is, however, displayed with the appropriate glyphs if Thread.CurrentThread.CurrentCulture is set accordingly and if the presentation engine supports digit substitution. (WPF do support it)
I looked at NativeDigits propety and the underlying field in Reflector and it doesn't seem to be used by anything when it comes to formatting (although Used by analysis in Reflector is not guaranteed to be 100% full). So it is possible that these values are there just for reference or something like that.
You can use your own IFormatProvider implementation by using the string output of ToString(culture) and manually replacing all digits by corresponding values from NativeDigits array. Although I'm afraid it's not the answer you were looking for..
Maybe what you need is this:
var number = 123.5;
var culture = CultureInfo.CreateSpecificCulture("prs-AF");
var text = String.Format(culture, "{0}", number);
Console.WriteLine(text);

Globalized custom number formatting - Variable decimal points

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.

Convert float to string with comma and dot

I have a nullable float. The internal decimal places can be separated with dot or comma e.g. 1.2 or 1,2. I need this float as a string to compare it to a Regex. If I use the Convert.toString method, the float with the comma is 12 and not 1.2. How can I convert a float to String without loosing the comma or the dot? I alredy tried to convert it with diffrent cultures.
Thanks for your help
A solution for this can be the following:
float? num = 1.2f;
string floatAsString = string.Format("{0:f}", num.Value);
Maybe you need to check if the HasValue property is true before you use the value. For more examples: http://alexonasp.net/samples/stringformatting/
String.Format() function with mask. But can you convert your strings to numbers rather than your numbers to strings, for purposes of the comparison? Does it have to be a regex comparison?
Try:
string s = yourFloat.ToString();
Using the invariant culture is recommended if you want to be sure that your output will be in the correct form, but I'd be surprised if there were a culture which doesn't output a comma or a dot.
I would also suggest not using regular expressions to validate the value of a float.
Are you certain that the textbox allows both "." and "," as a decimal-separator (as opposed to a grouping character, also known as a thousands-separator)?
When you are certain that you only get decimal separators and no grouping characters, replace any "," with a "." before using TryParse with an InvariantCulture to convert the string to a float.
OR use the same culture in the code as on the client side, so both will use the same decimal separators.
As others mentioned, a float doesn't have the concept of various decimal separators.
Ok I solved the problem. I did in my xaml a converter which only allows to enter values with commas as separator, so I dont need any checks if there are only two internal decimal places. Thanks for your help
If it's a WinForm Application, there's a static variable Application.CurrentCulture.NumberFormat.NumberDecimalSeparator.
Depending on it's value you get different results when converting ToString().
Try manipulating this parameter to achieve necessary result.

Categories