Currency String Formatting - c#

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.

Related

Currency formatting in .NET gives white space between amount and currency

I'm having issues with currency formatting in C#.
I'm using framework 2.0.
When I use this code:
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
price.Value.ToString("C", numberFormatInfo) seems to give me a string with a white space between amount and currency. That's horrible! I absolutely need a no-break space!
What is going on? Am I missing a format property or is it the C# standard?
Thanks for your help!
So basically you want price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');? At least that should be the code for non breaking space. – Corak
Exactly the same as above commentor, but using the asci-values instead; > price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160); (160 is a lot > easier to remember, atleast for me :)) – flindeberg
Adding an answer based on my interpretation of the question, which #Corak seems to share.
// Convert "breaking" spaces into "non-breaking" spaces (ie the html )
price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160);
Doing the same with unicode (courtesy of #Corak's link):
// Convert "breaking" spaces into "non-breaking" spaces without int cast to char
price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');
And btw (roslyn repl):
> '\u00A0' == (char) 160
true
And if you are going to be using it alot also get the extension method:
public static class StringExtensions
{// CurrencyType is your currency type, guessing double or decimal?
public static string ToCurrencyString(this CurrencyType value, IFormatInfo format)
{
return value.ToString("C", format).Replace((char) 32, (char) 160);
}
}
Use:
numberFormatInfo.CurrencyPositivePattern = 1;
For value 1 the format is n$ where $ is currency symbol and in your case its CHF
Formatting Types - MSDN
The CurrencyNegativePattern or CurrencyPositivePattern property, which
returns an integer that determines the following:
The placement of the currency symbol.
Whether negative values are indicated by a leading negative sign, a trailing negative sign, or parentheses.
Whether a space appears between the numeric value and the currency symbol.
Try the following code:
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
decimal d = 123.23M;
var temp = d.ToString("C", numberFormatInfo);
Output:
123,23CHF
You can replace it.
price.ToString("C", numberFormatInfo).Replace(" ", "")
or better set NumberFormatInfo.CurrencyPositivePattern to 1
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
Full example;
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
Console.WriteLine((1.5M).ToString("C", numberFormatInfo));
Output will be;
1,50CHF
Here a DEMO.
From Formatting Types
The CurrencyNegativePattern or CurrencyPositivePattern property, which
returns an integer that determines the following:
The placement of the currency symbol.
Whether negative values are indicated by a leading negative sign, a trailing negative sign, or parentheses.
Whether a space appears between the numeric value and the currency symbol.
You can configure the CurrencyPositivePattern and set it to something appropriate.
// whatever code you had
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencyPositivePattern = 1; // will format like 25.00CHF
Seems like by default it includes space when it comes to other currencies than $
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3",
CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
if you want to replace space, you can use as Soner said,
numberString.ToString("C", numberFormatInfo).Replace(" ", "");
In your global.asax ou can globaly change the culture and chose to remove the space like this :
CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("fr-FR"); //Get you own culture
cultureInfo.NumberFormat.CurrencyPositivePattern = 1; //To remove the space
Thread.CurrentThread.CurrentUICulture = cultureInfo; //Apply globaly to your application
Thread.CurrentThread.CurrentCulture = cultureInfo; //Apply globaly to your application
The clean solution is set your CurrencyPositivePattern to 0.
Example:
CultureInfo _culture= (CultureInfo) culture.Clone();
_culture.NumberFormat.CurrencyPositivePattern = 0;
var stringFormat = number.ToString("c3", _culture);
input: 1234567.845
output: $1.234.568
output: €1.234.568
output: S/1.234.568

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

Changing the number of integers on a output value after the decimal point

So I'm learning and practicing WP7 application development.
I'm working with integers (currency), and it seems to always display four integers after the decimal place. I'm trying to cut it down to just either ONE or TWO decimal places.
I've been trying to use the "my variable.ToString("C2")" (C for Currency, 2 for number of ints after the decimal)
I'm probably missing something obvious, but please help
decimal number = new decimal(1000.12345678);
string text = number.ToString("#.##");
Output:
1000,12
An other way:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
decimal val = new decimal(1000.12345678);
string text = val.ToString("c", nfi);
When formatting a currency, NumberFormatInfo allows specifying following properties as well:
CurrencyDecimalDigits
CurrencyDecimalSeparator
CurrencyGroupSeparator
CurrencyGroupSizes
CurrencyNegativePattern
CurrencyPositivePattern
CurrencySymbol
See Custom Numeric Format Strings on MSDN for more examples
The "C" format string defines the currency specifier as described on MSDN. This will include the currency symbol for the current culture, or for a specific culture if supplied, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));
// This gives $1234.56
In your case, it seems that you have a limited set of currency symbols that you support, so I would suggest using the fixed point format specifier "F" instead. By default this will give you 2 decimal points, but you can specify a number to vary this, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("F");
// This gives 1234.56
formatted = amount.ToString("F3");
// This gives 1234.567
Using the fixed point specifier will give you control over the number of decimal points and enable you to concatenate the currency symbol.
The only thing I would add to "sll" answer is to pay attention on Culture (they often forget to mantion this), like this (example)
string text = val.ToString("#.##", CultureInfo.InvariantCulture);
double total = 526.4134
string moneyValue = total.ToString("c");
This will display it in this format: $#.##

Replace dot(.) with comma(,) using RegEx?

I am working on a C# application. I want to change number decimal figure with comma(,) where i have dot(.) using regular expression.
For example:
Price= 100,00.56
As this international rule of representing numeric values but I Sweden they have different ways for numbers Like
Price= 100.00,56
So i want to change dot(.) into comma(,) and comma(,) into dot(.) using RegEx. Could guide me about this.
When formatting numbers, you should use the string format overload that takes a CultureInfo object. The culture name for swedish is "sv-SE", as can be seen here.
decimal value = -16325.62m;
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("sv-SE")));
Edit:
As #OregonGhost points out - parsing out numbers should also be done with CultureInfo.
Not a RegEx solution but from my experience - more correct:
public static string CheckDecimalDigitsDelimiter(this string instance)
{
var sv = new CultureInfo("sv-SE");
var en = new CultureInfo("en-US");
decimal d;
return (!Decimal.TryParse(instance, NumberStyles.Currency, sv, out d) &&
Decimal.TryParse(instance, NumberStyles.Currency, en, out d)) ?
d.ToString(sv) : // didn't passed by SV but did by EN
instance;
}
What does this method do? It ensures that if given string is incorrect Sweden string but is correct English - convert it to Sweden, e.g. 100,00 -> 100,00 but 100.00 -> 100,00.
You can do this even without regex. For example
var temp = price.Replace(".", "<TEMP>");
var temp2 = temp.Replace(",", ".");
var replaced = temp2.Replace("<TEMP>", ",");
Also have a look at
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
Not sure what 100,00.56 represents, did you mean 10.000,56?
To answer your question:
For such a simple task, why use RegEx? You can do it much easier:
string oldValue = "100,00.56";
char dummyChar = '&'; //here put a char that you know won't appear in the strings
var newValue = oldValue.Replace('.', dummyChar)
.Replace(',', '.')
.Replace(dummyChar, ',');
Edit
I agree with #Oded, for formatting numbers use the CultureInfo class.
Do not rely on RegExp for this kind of thing :) Use the build in cultures fx:
decimal s = decimal.Parse("10,000.56", NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"));
string output = s.ToString("N",CultureInfo.GetCultureInfo("da-DK"));
en-US will parse it correctly and da-DK uses the other kind of representation. I live in DK and therefore use that but you should use the culture which fits your output.

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

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

Categories

Resources