PSA: C# Convert number to currency string

Since I searched a bit on the forums and couldn’t find anything, I’d like to share a super simple way to convert a number to a string for currency in C#

IE: 568503.531 → $568,503.53

All you have to do is use the string.Format() function.

public static string valueToDollars(float num)
{
    return string.Format("{0:C}", num);
}

Input: 118009045.1
Output: $118,009,045.10
Doesn’t have to be a float value. string.Format will take any number format.

Just figured I’d let everyone know since some people try to make their own format function with lots of if statements and such.

2 Likes

PSA Part 2:
MSDN!

Here is a list of standard numeric format strings:
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

As well as a list of the custom numeric format string characters and how to use them:
https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

Note that ‘C’ will use the local computer region settings to determine symbols. You have to be careful if you’re representing ‘US dollars’ with your number, and you use the ‘C’ format for someone in the UK.

If it’s a qty that doesn’t matter that’s fine.

But if say it’s a ‘store front’ or something for a mobile game with downloadable content. It may be misleading to see a 2 quid purchase that’s actually 2 dollars.

Read to the bottom of the standard format page for an explanation about how to define with CultureInfo to use for formatting.

3 Likes

hello @lordofduct ,
this is working well when you try it on the given console , But in Unity it is not doing same

i’m just trying to add Currency sign $ to my given value

int num = 100000;
string val = string.Format(“{0:C}”, num);

Debug.Log(val) - $1,00,000.00, buy on mentioned link it gives - $100,000.00
problem is facing only while num is more than 6 digits . can you help me some thing into it ?

Thanks in advance.

I’m not sure which of the two numbers you actually get and which one you expect. As it was mentioned the currency format uses the local culture setting of your PC / device. If you use a Hindi culture setting it means you get the grouping

XX,XX,XX,XX,XXX.XX

as that’s the used grouping in that culture. You can read about that in the MSDN documentation here under point 5 about digid grouping. The majority of cultures use 3 digid grouping all the way. Hindi seem to only group the lowest 3 digits and from then on 2 digits. So my guess would be that if you currently get 100,000,00 and you want 1,00,000.00 you have set your machine culture to hindi. If it’s the other way round so you currently get 1,00,000.00 and you want to get 100,000.00 you would either set your machine culture to something different, or pass a format provider to your string.Format method and specify a culture with the desired format. The invariant culture may be the best choice here. Though if you want the numbers to be displayed how it’s actually common in the users culture, just don’t do anything different.