PDA

View Full Version : Currency place holder



rocg23
11-15-2006, 08:31 PM
ok, hopefully this will be my last question for day...

If there a way to make a total come out with cents places held?


$price = .50 * $o[count];
print "$o[count] at $.50 - $price";


so even if there is only 1 $price shows up as .5

mwinter
11-17-2006, 04:01 AM
If there a way to make a total come out with cents places held?

Do you mean to add trailing zeros? That is, "1." should be "1.00" and "0.3" should be "0.30".

Mike

rocg23
11-18-2006, 03:26 AM
Yes, that is exactly what I am looking for...thanks

djr33
11-18-2006, 04:30 AM
This is likely not the 'official' way, but here's an option and fairly simple...not sure if there's a faster/more efficient way (in server time):
<?
//$x is the value to be converted to "money" format
$x = $x*100;
$x = round($x);
$x = substr($x,0,strlen($x)-2).".".substr($x,strlen($x)-2);
//next line optional:
$x = "$".$x;
?>

Twey
11-18-2006, 12:55 PM
You should escape that dollar sign. Also, don't use short tags (<?, <?=?>, &c.) when you don't know the server, since it might not have them enabled.

djr33
11-18-2006, 01:13 PM
Oh, weird. The <? was a typo :p

escape fixed... just in single quotes instead due to that earier discussion...

Updated code:

<?php
//$x is the value to be converted to "money" format
$x = $x*100;
$x = round($x);
$x = substr($x,0,strlen($x)-2).'.'.substr($x,strlen($x)-2);
//next line optional:
$x = '$'.$x;
?>


Twey, does that seem like the logical solution for the problem? It's a pretty simple answer. Unless there's a specific function for this, I'd say it makes sense.
Would round($x,2) work? I think it would round correctly, but leave off trailing 0s... is that right?

Twey
11-18-2006, 02:00 PM
That's the way I'd do it, if money_format (http://uk2.php.net/money_format)() weren't available.

mwinter
11-19-2006, 05:04 PM
One should keep in mind that monetary calculations are best performed using scaled integers: floating point data types cannot represent all fractions exactly, unlike integers.



function formatMoney($number, $currency = '$') {
$string = str_pad(round($number), 3, '0', STR_PAD_LEFT);

return $currency . substr($string, 0, -2) . '.' . substr($string, -2);
}

If the first argument is a floating point number, it will rounded to an integer. For example, 1500.5 would be formatted as "$15.01".

Mike

rocg23
11-24-2006, 04:35 PM
Worked like a charm, thanks...now one of these days I have to actually learn what this all means.:eek:

djr33
11-24-2006, 09:04 PM
mike, that assumes that the input will be given in cents. I thought the question was related to something already in dollars, with the cents as the decimal.

mwinter
11-25-2006, 11:43 AM
mike, that assumes that the input will be given in cents.

Yes, of course. That's precisely how the function is defined.

Read my previous post again: monetary calculations should not be performed using floating-point numbers.

Mike