Represent Numeric Value with Typical Dollar Amount Format

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
}
}

How can I format currency with commas in C?

Your printf might already be able to do that by itself with the ' flag. You probably need to set your locale, though. Here's an example from my machine:

#include <stdio.h>
#include <locale.h>

int main(void)
{
setlocale(LC_NUMERIC, "");
printf("$%'.2Lf\n", 123456789.00L);
printf("$%'.2Lf\n", 1234.56L);
printf("$%'.2Lf\n", 123.45L);
return 0;
}

And running it:

> make example
clang -Wall -Wextra -Werror example.c -o example
> ./example
$123,456,789.00
$1,234.56
$123.45

This program works the way you want it to both on my Mac (10.6.8) and on a Linux machine (Ubuntu 10.10) I just tried.

Format number to currency in dplyr?

You can use the package scales:

Quote_Dollars <- scales::dollar_format()(data$Quote_Dollars)

dollar_format round to the closest by default.



Related Topics



Leave a reply



Submit