How to convert price by format - c#

I have encountered with a problem with pricing.
I need to format price input to be of the type XXXX.YY
the problem is, the input price can be of shape XXX,YY in europe or XX,XXX.YY if talking about big numbers.
Is there a JS or C# lib that helps there?
thanks

You should use Decimal.Parse rather than Double.Parse when dealing with currency values. (The Decimal type reduces the possibility of rounding errors etc.)
To answer your question about differing cultural currency formatting, from MDSN:
Parameter s is parsed using the
formatting information in a
NumberFormatInfo initialized for the
current system culture. For more
information, see CurrentInfo. To parse
a string using the formatting
information of some other culture, use
the Decimal.Parse(String,
IFormatProvider) or
Decimal.Parse(String, NumberStyles,
IFormatProvider) method.
In case you are not aware, the .NET framework automatically takes the "current system culture" from the current regional settings of the operating system. In Windows this can be viewed/changed by the computer user in the "Regional Settings" or similar.

for American / British format:
Double.Parse("123,456.78", new CultureInfo("en-US"));
for German format:
Double.Parse("123.456,78", new CultureInfo("de-DE"));
Hint: If you are storing / reading data from file/Database etc. it is generally advisable to make use of CultureInfo.InvariantCulture

Double.Parse("123,456.78")
will work in C#
http://msdn.microsoft.com/en-us/library/7yd1h1be.aspx
Then ToString it to the format you want:
String.Format("£{0:##.##}", number);

Related

Using invariant culture with IFormatProvider in DateTime.ParseExact

In the First overload of ParseExact method
public static DateTime ParseExact (string s, string format, IFormatProvider provider);
according to Microsoft:
If format is a custom format pattern that does not include date or time separators (such as "yyyyMMddHHmm"), use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the format pattern, specify the wider form, "HH", instead of the narrower form, "H".
In particular if we use stander format pattern we could use any other cultures
what is the really purpose of using invariant culture and widest custom specifier if we use custom format pattern that does not include date or time separators if we use?
The purpose of InvariantCulture is to have a well-known way to format dates and numbers, that does not depend on the system or user locale.
You should use it every time you format something that is not meant to be parsed by humans. For example in a JSON or XML file you want to store the date in ISO format so there is no ambiguity. On the other hand if you display the date on the screen, you generally respect the user's choice of culture and display it in the preferred way.
If you use a custom format, then it would surely be good if the resulting string can be parsed back into the exact same date and time. In order to do that without separators you have to use fixed length strings for each component.
// omitting CultureInfo.InvariantCulture for brevity
var dt = new DateTime(2018,1,2,3,45,6);
dt.ToString("yyyyMMddHHmmss") // returns "20180102034506"
dt.ToString("yyyyMdHms") // returns "2018123456"
You can easily see that the second one is not unique, i.e. there are other dates which will return the same string. In order to avoid that you use the wider form of each component.
the real purpose of invariant culture is taken taken from a an answer in this question, as it describes it's purpose best:
Not all cultures use the same format for dates and decimal / currency
values.
This will matter for you when you are converting input values (read)
that are stored as strings to DateTime, float, double or decimal. It
will also matter if you try to format the aforementioned data types to
strings (write) for display or storage.
If you know what specific culture that your dates and decimal /
currency values will be in ahead of time, you can use that specific
CultureInfo property (i.e. CultureInfo("en-GB")). For example if you
expect a user input.
The CultureInfo.InvariantCulture property is used if you are
formatting or parsing a string that should be parseable by a piece of
software independent of the user's local settings.
To sum this up, the invariant culture will help with conversions be a string stored to float, decimal or asDateTime, it is here also to help when you are trying to format or parse a string that should be parseable by a piece of software independent of the user's local settings, as the quote said and that is what
widest custom specifier
means by that.

CultureInfo.InvariantCulture in .ToString()

I am currently fixing FxCop issues so I encountered issue where I have to provide cultureinfo when converting a string using ToString() .
Currently in my code nothing we are passing as IFormatProvider so I have read some msdn articles saying that when you don't pass any value for cultureinfo it will assign a default value and when you specify CultureInfo as InvariantCulture it will be independent of any culture.
My question is, "Are default and CultureInfo.InvariantCulture one and the same? Can I replace all my code from default to InvariantCulture?"
Ex :
int st = 123;
String s = st.ToString(123); // this will be taken as default
String s = st.ToString(123, CultureInfo.InvariantCulture); // culture is specified externally
Are the second and third lines equivalent?
Is default and CultureInfo.InvariantCulture are one and the same?
No, absolutely not. The default culture depends (initially) on the operating system settings. The invariant culture is meant to be a "neutral" culture.
Your example of 123 isn't a great one, because most (all?) cultures will represent integers the same way - at least until you get into formats with grouping separators etc. (I don't think .NET supports non-Arabic numerals when formatting integers.)
Compare that with formatting a decimal value, for example:
decimal x = 123.45m;
Console.WriteLine(x.ToString()); // Might be 123,45
Console.WriteLine(x.ToString(CultureInfo.InvariantCulture)); // Always 123.45
If you run the above code in (say) France, the default culture will be French, which uses a comma as a decimal separator - so it will print out "123,45".
The rule of thumb to remember is that the invariant culture is suitable for machine-to-machine communications (e.g. formatting values in JSON or XML) whereas other cultures are more suitable for displaying information directly to users.
Although the default culture is originally based on the operating system settings, it can be changed using Thread.CurrentCulture and Thread.CurrentUICulture; the latter is used for looking up translated resources, whereas the former is used for formatting decisions like the above. You can set these properties on any thread, but typically you'd use Thread.CurrentThread.CurrentCulture = ...
No, they are not the same.
The first will take the regional settings from the computer or the culture settings from the application thread running.
The second one will take the English language, according to MSDN:
The invariant culture is culture-insensitive; it is associated with the English language but not with any country/region.

How to use CultureInfo to format deprecated currencies?

In dotnet, the recommended way of formatting currencies in a culture-specific way, is (as far as I can find):
using System.Globalization
var info = CultureInfo.GetCultureInfo("en-GB")
return string.Format(info, "{0:c}", 1234.5678)
This returns:
£1,234.57
However. No specific currency is given here. So if Great Britain ever converts to Euro, the same method would suddenly return something like:
€ 1,234.57
This has just happened to Latvia. This year, it converted to the euro. Various systems contain both amounts in letvian lats and euros. I need to be able to still print and format old currencies. And I need to be sure new currencies can also be handled. This formatting is not just about the symbol, but also about the placement (before, after, with or without space) and the local number format (decimal separator and thousands separator).
Every amount in our database has a currency (e.g. EUR) and a corresponding culture (e.g. nl-NL). Euro amounts are formatting differently depending on if they originate from our German or our Dutch office. (they both use euros, but format the amounts differently)
Does dotnet provide access to older currencies?
What is a future-proof way of writing the formatting amounts?
Right now, the only way I can think of, is to copy the culture-database to my database.
You can create a custom CultureInfo (by cloning one and modifying) which uses a different currency symbol/format (ie. set its NumberFormat to a different instance of NumberFormatInfo).
Then pass this CultureInfo to formatting functions as needed.
As the comment to the question notes, .NET (and Windows in general) doesn't provide historic data (similarly for time zones but there's a library for that). In the cases you need you'll need to hold enough data yourself.
Remember ISO-4217 currency codes are not reused under such a change, so holding that against amounts allows you to format correctly. Additionally just because a country formats their currency amounts one way doesn't mean everyone does. Eg. 25 French Francs was be "FF25.00" in the UK but "25FF00" or "FF25,00" in other locales. (EDIT: I note you covered this last paragraph in the question.)
Of course, the simplest way is to not use the locale-specific currency format, but rather to format the amount as a simple number and pre- or suffix it with the ISO currency code. The convention
------------
Sum: ATS 1.376,00 (= EUR 100,00)
is commonly found on invoices (using locale de-AT as an example).
If you want to use the built-in currency formatting options, I would suggest to replace the currency symbol with the one stored in the database. I.e., in your currency table, you'd need to map currencies to symbols:
EUR -> €
ATS -> S
...
and then you'd replace myCultureInfo.NumberFormat.CurrencySymbol with the one in the database. That way, you ensure that a value is never shown with the wrong currency symbol.
If you are targeting Windows 8 or above, this deficiency is addressed by the Windows.Globalization.NumberFormatting.CurrencyFormatter. It requires that you provide the explicit currency and you can also explicitly provide a language.

CultureInfo.InvariantCulture in plain english

I know that culture rules for dates/numbers is enough for an entire book, I think I have a simple question though..
Does using InvariantCulture basically mean that you explicitly define what culture the value (date/number/whatever) will be inputted/displayed as? And it overrides any other culture setting (such as the user agent's setting)?
If an app is built for an audience of one and only one culture, would it make sense to use InvariantCulture and define how you want values inputted/displayed each time?
Does using InvariantCulture basically mean that you explicitly define what culture the value (date/number/whatever) will be inputted/displayed as?
No. It's just a culture which is a bit like US English, except for a few things like currency sign. It's usually used to format/consume text which is to be understood or was produced by another computer rather than a human.
If an app is built for an audience of one and only one culture, would it make sense to use InvariantCulture and define how you want values inputted/displayed each time?
No, you would use the relevant CultureInfo for that culture. You could also explicitly define the format for dates etc, but that's an orthogonal concern. It may well be best to use one of the predefined standard formats for that culture, but if none of those meet your needs you can always be explicit.
InvariantCulture is Independent of any culture or any factor.
For example if you're using new CultureInfo("en-US") it will get you US English Culture(Which may not be actual US English Culture because OS gives you option to change these setting in Control Panel) it will return the modified version of Culture of "en-US" if any custom formatting applied to it.
In other words InvariantCulture will always gives you a Culture which can never be changed across Systems.
Let's assume you want to serialize some value(say double) and pass to another application or some other thread which is running in different culture leads to serious problems.
Consider the following code
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr");
double source = 455.62d;
string serialized = source.ToString();//455,62 since `, is the decimal seperator` in "fr"
Thread t = new Thread((x) =>
{
double deserialized = double.Parse(((string)x));
Console.WriteLine(string.Format("Deserialized value is {0}", deserialized));//outputs 45562
});
t.CurrentCulture = new CultureInfo("en-US");
t.Start(serialized);
numbers matters more right? consider this string denotes AccountBalance?
Hope this helps
With specific regard to DateTime, the best advice I can give is to use CultureInfo.InvariantCulture for ParseExact and ToString when you have an exact format in mind. (You can also use it with Parse if you happen to know that your input format matches the invariant culture's formats, but I typically avoid this.)
Don't use the invariant culture when interacting with a user.
Keep in mind that the culture contains several items, including the ordering of day/month/year parts, the date and time part separator characters, the character encoding, and the language-specific names of the days of the week, months of the year, and abbreviations including am/pm.
Some examples of when you should use the invariant culture:
Files on disk, especially text files of a predefined format
External APIs, especially JSON or XML
Unit tests, unless you are specifically testing culture issues
Some examples of when you should use a specific culture such as en-US:
User Interface
Reports

String.Format and culture

When formatting a string as opposed to a DateTime, does the culture ever come into play? Are there any examples of strings that would be formatted differently with two different cultures?
I don't believe so in the current Framework. But if Microsoft ever implements this suggestion on the Connect feedback site, it includes a suggestion to have a format specifier to force upper case:
String.Format("{0:U}", "SomeString") => "SOMESTRING"
Such formatting would be culture-specific.
If you are displaying a string that is stored as a resource it will make a difference if you have separate strings for different cultures (you'd use CultureInfo.CurrentUICulture). For example error messages accessed via a ResourceManager.
String.Format("{0}", "This string") - which I believe is what you're implying by your question, is not affected by the culture.
There are many scenarios when you need culture based formatting.
For example: - Number Format
5.25 in English is written as 5,25 in French
So, if you want to display French formatted number in your program which is in English culture the culture based string format comes into action.

Categories