Currency format for display
Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.
You can use it with either String.Format
or the overloaded ToString
method for a numeric type.
For example:
decimal value = 12345.6789M; // Be sure to use Decimal for money values. Do not use IEEE-754 types such as float (System.Single) and double (System.Double) as they can only store approximate values.
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
How to format numbers as currency strings
Ok, based on what you said, I'm using this:
var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);
var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);
return '£ ' + intPart + DecimalSeparator + decPart;
I'm open to improvement suggestions (I'd prefer not to include YUI just to do this :-) )
I already know I should be detecting the "." instead of just using it as the decimal separator...
How to format decimals in a currency format?
I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that.
If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.
Something like this would do the trick:
public String formatDecimal(float number) {
float epsilon = 0.004f; // 4 tenths of a cent
if (Math.abs(Math.round(number) - number) < epsilon) {
return String.format("%10.0f", number); // sdb
} else {
return String.format("%10.2f", number); // dj_segfault
}
}
C# currency formatting (C2)
Check out this link for currency formatting for certain cultures.
Here's another that has a list for formatting numeric strings.
Hope this helps! :D
Currency format without symbol
DataTypeAttribute
with DataType.Currency
enum value sets an input as currency value with symbol mark depending on current culture or globalization attribute being set in web.config. Based from .NET numeric format strings, there are multiple representations you can use with DisplayFormatAttribute
using DataFormatString
:
1. Standard Numeric Format
[DisplayFormat(DataFormatString = "{0:N2}")]
public float PrecoUsd { get; set; }
2. Custom Numeric Format
// using placeholder '#'
[DisplayFormat(DataFormatString = "{0:#,#.00}")]
public float PrecoUsd { get; set; }
// using placeholder '0'
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
public float PrecoUsd { get; set; }
Both of them can use DisplayFor
or EditorFor
to display values:
@Html.DisplayFor(model => model.PrecoUsd)
@Html.EditorFor(model => model.PrecoUsd)
NB: Usage of #,#.##
returns 3,000 instead of desired 3,000.00 (see this demo to prove it). As for displaying currency symbol separated from number input, use DisplayAttribute
e.g. [Display(Name = "US$")]
.
How to display number in money format
As I understand, this is an Indian style of formatting the currency.
Console.WriteLine(intValue.ToString("N1", CultureInfo.CreateSpecificCulture("hi-IN")));
where intValue is the number you want to format.
For the same input in your question, you should get exactly "1,23,45,678".
How to format display String to currency in C#
Try:
display = string.Format("Service Amount: {0}",service.ToString("C"));
Console.WriteLine(display);
You can also look at StringBuilder for building strings or String.Format
Formatting currency using display template in MVC
How about HtmlHelper
that checks the ViewData["woCurrency"]
automatically and outputs the correct result?
public static string Currency(this HtmlHelper helper, decimal data, string locale = "en-US", bool woCurrency = false)
{
var culture = new System.Globalization.CultureInfo(locale);
if (woCurrency || (helper.ViewData["woCurrency"] != null && (bool)helper.ViewData["woCurrency"]))
return data.ToString(culture);
return data.ToString("C", culture);
}
Then:
@Html.Currency(Model.Money);
Change currency format to show 4 decimal places instead of 2 globally
You can't modify the default behavior of the format specifier, but you can do a a global search-and-replace in your project. Assuming you're using Visual Studio, you can do a global search-and-replace (Ctrl-Shift-H) and replace .ToString("C")
with .ToString("C4")
.
Related Topics
How to Disable a System Device Programmatically
How to Handle Null or Optional Dll Struct Parameters
Checking User Name or User Email Already Exists
Combobox- Selectionchanged Event Has Old Value, Not New Value
JSON String to CSV and CSV to JSON Conversion in C#
Why Can't I Access C# Protected Members Except Like This
I Didn't Find "Zipfile" Class in the "System.Io.Compression" Namespace
Force Download of a File on Web Server - Asp .Net C#
Shellexecute Equivalent in .Net
What Is the Point of Lookup<Tkey, Telement>
How to Find Fqdn of Local MAChine in C#/.Net
Dependency Injection Using Azure Webjobs Sdk
How to Read All Files Inside Particular Folder
Can't Get SQL Server Compact 3.5/4 to Work with Asp .Net MVC 2