I am looking for a strategy to implement different currencies in my system.
For GB I use pounds locale and it works ok with numbers like "7.55", but as soon I change locale to Spanish for example I get the "7,55" number and I cannot handle it.
So the first thing is that I calculate some amount with JavaScript client side and JavaScript cannot calculate comma numbers, nor I can parseFloat, nor converting to decimal number if I don't replace commas with numbers like:
input.val().replace(',', '.');
I mean I don't understand how to handle this properly in scenarios when you have to make payment. When to convert for calculations, etc.
Is there any proper way to do this in .net with JavaScript help? Just need some tips.
In c#, you can use CultureInfo.InvariantCulture for this. You have a full snippet about currency here.
string str = "42.5";
float numFloat = float.Parse(str, CultureInfo.InvariantCulture);
Learn more from the msdn.
Related
I have the format string ######.00 used for formatting decimals in C#. I need to change it so that it omits the period but keeps the digits following the period. Can I accomplish this just by changing the format? I've searched, but haven't been able to find a solution online.
I found this answer to a very similar question, but it involves multiplying the decimal by 100 before formatting it. I'm not able to manipulate the number going in, nor the resulting string because I don't have access to them. This is because we're using a function from a third-party library that fetches the number from elsewhere and displays it formatted to the UI. I can only provide it with a format string. (If manipulating the number or resulting string is the only way to get it in the format we can probably do it, it would just take a good deal of refactoring, so I wanted to see if there's a simpler solution first. Hence the constraints.)
Just as an example of the output I'm looking for, consider the following code:
var myFormat = "{0:######.00}";
Console.WriteLine(string.Format(myFormat, 1234.1234));
Console.WriteLine(string.Format(myFormat, 5));
The code above currently outputs 1234.12 and 5.00, but I would like it to output 123412 and 500 just by changing myFormat. Is there a way to do this?
If only the format string is what you can change, there's probably no way to remove the dot.
However, you can implement your own Formatter, as MSDN's example.
string.Format(new CustomerFormatter(), "{0}", 1234.1234)
Given the input 123.45, I'm trying to get the output 123,45 via String.Format.
Because of the system I'm working in, the actual format strings (e.g. {0:0.00}) are saved in a config file and transformed later down the pipeline.
Editing the config file to add a new format is "safe" and I can get this through quite quickly. Editing the actual parser later down the line is "risky" so will need a more significant QA resource and I need to avoid this.
As a result, some caveats:
I only have access to string.Format(pattern, input). No overloads.
I cannot send a localisation. I know that if I send string.Format(new System.Globalization.CultureInfo("de-DE"), "{0:0.00}", 123.45) then I've got what I need. But I cannot pass the localisation.
So can it be done?
Is there any format I can pass to string.Format which will transform 123.45 into 123,45?
If you can you multiply the input by 100 then the following should work:
double input = 123.45;
string pattern = "{0:###\\,##}";
var result = String.Format(pattern, input*100);
Just for the fun of it :)
double value =123.45;
Console.WriteLine(String.Format("{0:#0.00}\b\b\b,", value));
This of course only works when there is a cursor, like in the console, otherwise the backspace control characters have no effect.
Sorry, but i can't think of a real way in accomplishing this.
Just something that i was wondering about.
In Europe the comma us mostly used for decimals (like 20,001) but outside Europe the point is mostly used (like 20.001)
How does c# handle this ?
In case of a application that will be used by Europe and non-Europe people, do you need to worry about the above when programming ?
Just curious about this.
As far as the programming language is concerned, the decimal point separator is always ., and the punctuation used to separate function arguments is always ,. Changing that based on the spoken language of the programmer would be too confusing.
For the user interface, there are formatting functions in the CultureInfo class that can produce a floating point number representation that uses the decimal point separator and thousands separator of your choice. (Or, for cultures that group digits of a number differently than in triplets, the formatting functions can handle that too.)
CultureInfo handles that situation.
Take a look at this
// format float to string
float num = 1.5f;
string str = num.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.5"
string str = num.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat); // "1,5"
Yes, c# (and really, the whole .NET framework) have the concept of Cultures for this purpose:
http://msdn.microsoft.com/en-us/library/bz9tc508.aspx
and
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=VS.100).aspx
You should use CultureInfo Class to handle it. Just read and write with correct formatter.
That depends on what exactly you do... .NET is usually aware of the current settings of the machine/OS and uses those...
You should look into this and see whether any of it is relevant in your case...
I am formatting the currency using Tostring() method i m using following syntax
ToString('##.##') it is working perfectly but in case of round number it remove last 2 zero
like for 100 it does not show 100.00 is shows 100.
how can i format in that way means
input desired output
100 100.00
100.10 100.10
Try "##.00" instead.
That will force two digits after the decimal separator.
You can also use ToString("C") to use the culture specific format in Windows directly.
First google result.
String.Format("{0:C}", x.ToString());
http://www.howtogeek.com/howto/programming/format-a-string-as-currency-in-c/
You can use :
.ToString("C")
Hope it helps.
Also, if you don't want the currency sign ($ in the US) added that "C" gives, you can also use "F2", which is "fixed number with 2 decimal places". It also has the advantage of giving you a thousands separator when you results go over 1,000.00.
This might help. Might be more than you need, but it takes globalization into account which might be necessary. "C" is also a short-cut currency format string that might get you further along.
What is the best way to parse a float in CSharp?
I know about TryParse, but what I'm particularly wondering about is dots, commas etc.
I'm having problems with my website. On my dev server, the ',' is for decimals, the '.' for separator. On the prod server though, it is the other way round.
How can I best capture this?
I agree with leppie's reply; to put that in terms of code:
string s = "123,456.789";
float f = float.Parse(s, CultureInfo.InvariantCulture);
Depends where the input is coming from.
If your input comes from the user, you should use the CultureInfo the user/page is using (Thread.CurrentThread.CurrentUICulture).
You can get and indication of the culture of the user, by looking at the HttpRequest.UserLanguages property. (Not correct 100%, but I've found it a very good first guess) With that information, you can set the Thread.CurrentThread.CurrentUICulture at the start of the page.
If your input comes from an internal source, you can use the InvariantCulture to parse the string.
The Parse method is somewhat easier to use, if your input is from a controlled source. That is, you have already validated the string. Parse throws a (slow) exception if its fails.
If the input is uncontrolled, (from the user, or other Internet source) the TryParse looks better to me.
If you want persist values ( numbers, date, time, etc... ) for internal purpose. Everytime use "InvariantCulture" for formating & parsing values. "InvariantCulture" is same on every computer, every OS with any user's culture/language/etc...
string strFloat = (15.789f).ToString(System.Globalization.CultureInfo.InvariantInfo);
float numFloat = float.Parse(System.Globalization.CultureInfo.InvariantInfo, strFloat);
string strNow = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantInfo);
DateTime now = DateTime.Parse(System.Globalization.CultureInfo.InvariantInfo, strNow);
You could always use the overload of Parse which includes the culture to use?
For instance:
double number = Double.Parse("42,22", new CultureInfo("nl-NL").NumberFormat); // dutch number formatting
If you have control over all your data, you should use "CultureInfo.InvariantCulture" in all of your code.
Use a neutral culture (or one you know) when parsing with Try/Parse.
Pass in a CultureInfo or NumberFormatInfo that represents the culture you want to parse the float as; this controls what characters are used for decimals, group separators, etc.
For example to ensure that the '.' character was treated as the decimal indicator you could pass in CultureInfo.InvariantCulture (this one is typically very useful in server applications where you tend to want things to be the same irrespective of the environment's culture).
Try to avoid float.Parse, use TryParse instead as it performs a lot better but does the same job.
this also applies to double, DateTime, etc...
(some types also offer TryParseExact which also performs even better!)
The source is an input from a website. I can't rely on it being valid. So I went with TryParse as mentioned before.
But I can't figure out how to give the currentCulture to it.
Also, this would give me the culture of the server it's currently running on, but since it's the world wide web, the user can be from anywhere...
you can know current Cuklture of your server with a simple statement:
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
Note that there id a CurrentUICulture property, but UICulture is used from ResourceMeanager form multilanguages applications. for number formatting, you must considere CurrentCulture.
I hope this will help you
One approach is to force localization to use dot instead of comma separator - this way your code will work identically on all windows machines independently from selected language and settings.
This approach is applicable to small gained applications, like test applications, console applications and so on. For application, which was localization in use this is not so useful, but depends on requirements of application.
var CurrentCultureInfo = new CultureInfo("en", false);
CurrentCultureInfo.NumberFormat.NumberDecimalSeparator = ".";
CurrentCultureInfo.NumberFormat.CurrencyDecimalSeparator = ".";
Thread.CurrentThread.CurrentUICulture = CurrentCultureInfo;
Thread.CurrentThread.CurrentCulture = CurrentCultureInfo;
CultureInfo.DefaultThreadCurrentCulture = CurrentCultureInfo;
This code forces to use dot ('.') instead of comma, needs to be placed at application startup.
Since you don't know the web user's culture, you can do some guesswork. TryParse with a culture that uses , for separators and . for decimal, AND TryParse with a culture that uses . for separators and , for decimal. If they both succeed but yield different answers then you'll have to ask the user which they intended. Otherwise you can proceed normally, given your two equal results or one usable result or no usable result.