Custom Currency symbol and decimal places using decimal.ToString("C") and CultureInfo - c#

I have a problem with decimal.ToString("C") override.
Basically what I wants to do is as follows:
CultureInfo usCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = usCulture;
NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
LocalFormat.CurrencySymbol = "RM";
I wants to make above code a function (override ToString("C")) whereby when the following code get executed:
decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("C");
The results would be RM4,900.00 instead of $4,900.00
How do I create an override for decimal.ToString("C") that would solve my problem
Thanks in advance.

To get a format like RM 11,123,456.00 you also need to set the following properties
CurrentCulture modified = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
Thread.CurrentThread.CurrentCulture = modified;
var numberFormat = modified.NumberFormat;
numberFormat.CurrencySymbol = "RM";
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencyGroupSeparator = ",";
If you do that at application startup then that should make ms-MY format like en-US but with the RM currency symbol every time you call the ToString("C") method.

If I understand your question correctly what you want is to replace the $ with RM. If so, you need to pass the custom format...
lblPaids.Text = paid.ToString("C", LocalFormat);

use this format string :
#,##0.00 $;#,##0.00'- $';0 $
decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("#,##0.00 $;#,##0.00'- $';0 $");

You can use the Double.ToString Method (String, IFormatProvider) https://msdn.microsoft.com/en-us/library/d8ztz0sa(v=vs.110).aspx
double amount = 1234.95;
amount.ToString("C") // whatever the executing computer thinks is the right fomat
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie")) // €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es")) // 1.234,95 €
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) // £1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca")) // $1,234.95

lblPaids.Text = paid.ToString("C",usCulture.Name);
Or
lblPaids.Text = paid.ToString("C",LocalFormat.Name);
must Work

Related

How take decimal symbol (string/char) in current region?

I try find this in Windows.Globalization, but didn't find.
Is it possible to get it or not? If not? Are there alternative ways of formatting in different regions?
Example: Convert.ToDouble("0" + Decimal_Symbol.ToString() + "0001");
It's in System.Globalization, not Windows.Globalization:
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
you will find above an example of how to use the french culture, after according to your need you can change the culture.
decimal decimalNumber = 1000.1m;
var culture = CultureInfo.GetCultureInfo("fr-fr");
Console.WriteLine(decimalNumber.ToString(culture));
You can try to use CultureInfo, and the ToString overload that asks number formatting.
In this example, N4 is a number displayed with 4 decimals:
var MyNumber = 123.4567m;
var MyCulture = new System.Globalization.CultureInfo("pt-BR"); // en-US fr-FR
var Result = MyNumber.ToString("N4", MyCulture);
char regionSymbol = (1.1).ToString()[1];

Currency String Formatting

I am a student in school for c# and have been given a problem to solve. Within the problem, you have to format currency. I have figured out how to format $, but still have yet to figure out Yen, and Baht.
int num1;
string fNum;
string aNum;
num1 = 1255;
fNum = num1.ToString("C"); // "C" Changes Number to $$
aNum = "US:";
Console.WriteLine(aNum + fNum);
This has given me
US : $1,255.00 .
How do I format BAHT and YEN?
Just use an overload of ToString() and into second parameter culture pass specific culture for Yen and Baht.
Here is an example for $ and £
specifier = "C";
culture = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine(value.ToString(specifier, culture));
// Displays: $16,325.62
culture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine(value.ToString(specifier, culture));
// Displays: £16,325.62
Source: Decimal to string help
First you need to add the namespace:
using System.Globalization;
then add:
string jp = num.ToString("C", new CultureInfo("ja-JP"));
For the baht is the same just change the symbols.

Double to string with culture and only one decimal place

I need to keep culture when converting double to string and also round to only one decimal place.
Converting double to string with culture:
((12275454.8).ToString("N", new CultureInfo("sl-SI")));
Gives output:
12.275.454,80
Converting double to string with only one decimal:
string.Format("{0:F1}",12275454.8)
Gives output:
12275454.8
The second output is without culture, the first output is not rounded to one decimal place. How to combine both methods?
Just use the format string of your second example in your first example, i.e.:
((12275454.8).ToString("N1", new CultureInfo("sl-SI")));
Edit: Changed format from F1 to N1 as per request. The difference between both is that N additionally uses thousands separators, whereas F does not. For details see https://msdn.microsoft.com/en-US/library/dwhawy9k(v=vs.110).aspx
You can set "sl-SI" culture as a default one:
using System.Threading;
...
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("sl-SI");
string test = string.Format("{0:F1}",12275454.8);
Add try..finally if you want "sl-SI" culture for a block of code only:
var savedCulture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("sl-SI");
// Let's work with "sl-SI" for a while
string test = string.Format("{0:F1}",12275454.8);
...
}
finally {
Thread.CurrentThread.CurrentCulture = savedCulture;
}

c# decimal toString() conversion with comma(,)

c# decimal.toString() conversion problem
Example: I have a value in decimal(.1)
when I convert decimal to string using toString() it returns (0,10). Instead of .(DOT) it returns ,(COMMA).
I believe this is to do with the culture/region which your operating system is set to. You can fix/change the way the string is parsed by adding in a format overload in the .ToString() method.
For example
decimalValue.ToString(CultureInfo.InvariantCulture);
you have to define the format, it will depend in your local setting or
define the format, using something like this
decimal.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
cheers
For this to be happening, the thread's current culture must be one that uses a separator of comma instead of dot.
You can change this on a per ToString basis using the overload for ToString that takes a culture:
var withDot = myVal.ToString(CultureInfo.InvariantCulture);
Alternatively, you can change this for the whole thread by setting the thread's culture before performing any calls to ToString():
var ci = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
var first = myVal.ToString();
var second = anotherVal.ToString();
For comma (,)
try this:
decimalValue.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("tr-tr"))
Then your current culture's NumberDecimalSeparator is , instead of ..
If that's not desired you can force the dot with CultureInfo.InvariantCulture:
decimal num = 0.1m;
string numWithDotAsSeparator = num.ToString(CultureInfo.InvariantCulture);
or NumberFormatInfo.InvariantInfo
string numWithDotAsSeparator = num.ToString(NumberFormatInfo.InvariantInfo)

String format currency

I have this line
#String.Format("{0:C}", #price)
in my razor view. I want it to display a dollar sign in front of the price but instead it display a pound sign. How do I achieve this?
I strongly suspect the problem is simply that the current culture of the thread handling the request isn't set appropriately.
You can either set it for the whole request, or specify the culture while formatting. Either way, I would suggest not use string.Format with a composite format unless you really have more than one thing to format (or a wider message). Instead, I'd use:
#price.ToString("C", culture)
It just makes it somewhat simpler.
EDIT: Given your comment, it sounds like you may well want to use a UK culture regardless of the culture of the user. So again, either set the UK culture as the thread culture for the whole request, or possibly introduce your own helper class with a "constant":
public static class Cultures
{
public static readonly CultureInfo UnitedKingdom =
CultureInfo.GetCultureInfo("en-GB");
}
Then:
#price.ToString("C", Cultures.UnitedKingdom)
In my experience, having a "named" set of cultures like this makes the code using it considerably simpler to read, and you don't need to get the string right in multiple places.
As others have said, you can achieve this through an IFormatProvider. But bear in mind that currency formatting goes well beyond the currency symbol. For example a correctly-formatted price in the US may be "$ 12.50" but in France this would be written "12,50 $" (the decimal point is different as is the position of the currency symbol). You don't want to lose this culture-appropriate formatting just for the sake of changing the currency symbol. And the good news is that you don't have to, as this code demonstrates:
var cultureInfo = Thread.CurrentThread.CurrentCulture; // You can also hardcode the culture, e.g. var cultureInfo = new CultureInfo("fr-FR"), but then you lose culture-specific formatting such as decimal point (. or ,) or the position of the currency symbol (before or after)
var numberFormatInfo = (NumberFormatInfo)cultureInfo.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "€"; // Replace with "$" or "£" or whatever you need
var price = 12.3m;
var formattedPrice = price.ToString("C", numberFormatInfo); // Output: "€ 12.30" if the CurrentCulture is "en-US", "12,30 €" if the CurrentCulture is "fr-FR".
You need to provide an IFormatProvider:
#String.Format(new CultureInfo("en-US"), "{0:C}", #price)
Personally i'm against using culture specific code, i suggest doing:
#String.Format(CultureInfo.CurrentCulture, "{0:C}", #price)
and in your web.config do:
<system.web>
<globalization culture="en-GB" uiCulture="en-US" />
</system.web>
Additional info:
https://msdn.microsoft.com/en-us/library/syy068tk(v=vs.90).aspx
For razor you can use: culture, value
#String.Format(new CultureInfo("sv-SE"), #Model.value)
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450
Console.WriteLine();
Console.WriteLine(".ToString(\"F\") Formates With out Currency Sign");
Console.WriteLine(value.ToString("F"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F1"));
//OutPut : 12345.1
Console.WriteLine(value.ToString("F2"));
//OutPut : 12345.12
Console.WriteLine(value.ToString("F3"));
//OutPut : 12345.123
Console.WriteLine(value.ToString("F4"));
//OutPut : 12345.1234
Console.WriteLine(value.ToString("F5"));
//OutPut : 12345.12345
Console.WriteLine(value.ToString("F6"));
//OutPut : 12345.123450
Console.Read();
Output console screen:
Use this it works and so simple :
var price=22.5m;
Console.WriteLine(
"the price: {0}",price.ToString("C", new System.Globalization.CultureInfo("en-US")));
For those using the C# 6.0 string interpolation syntax: e.g: $"The price is {price:C}", the documentation suggests a few ways of applying different a CultureInfo.
I've adapted the examples to use currency:
decimal price = 12345.67M;
FormattableString message = $"The price is {price:C}";
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();
var specificCulture = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCulture);
string messageInInvariantCulture = FormattableString.Invariant(message);
Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCulture,-10} {messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10} {messageInInvariantCulture}");
// Expected output is:
// nl-NL The price is € 12.345,67
// en-IN The price is ₹ 12,345.67
// Invariant The price is ¤12,345.67

Categories

Resources