views:

369

answers:

3

I have a list of values such as "12000","12345","123456" that need to be converted to currency ("120.00", "123.45", "1234.56"). The only way I know is to convert the value to a string, copy the first strlen()-2 characters to one string (dollars) and the remainging two digits to another string(cents) and then write them as the following:

printf("%s.%s", dollars, cents);
+6  A: 
printf("$%.2f", value/100);
Phaedrus
If your currency is in cents, divide by 100 before using Fistandantilus's command.
Brian
Actually you want to divide by 100.0f to ensure that it is float. If 'value' is an int then value/100 will also be an 'int'.
codelogic
Money and floating point values cause problems. This is because 1/100 can not be converted to a floating point value evenly. Fistandantilus has it right.
lillq
Try compiling "printf("%.2f\n", 54321/100);" in gcc. If the format string is %f, the argument has to be a float.
codelogic
no fistandantilus has it wrong oO
Johannes Schaub - litb
+3  A: 

Don't use floats for storing or representing monetary amounts. Use longs (if you need more than 4 billion cent use llongs). Its usually a good idea to represent currency in its minimum usable unit, example use 10000 to represent 100Euro). Then the correct way to format these values (assuming 100 cent to the euro or dollar) is:

printf( "%d.%02d", value/100, value%100);

Hope that makes sense...

Calculations with currency values is a complex subject but you cant go far wrong is you always aim to have a rounded answer to the nearest currency unit (cent for example) and always make sure that rounding errors are calculated for (example, to divide 1 dollar three ways you should end up with 33+33+34 or 33+33+33+1).

Tim Ring
A: 

to prefix values less than $1.00 with 0, use:

printf( "$%0.2f", value / 100.0 );

This will result in $0.25 if value = 25