简体   繁体   中英

printing with the penny value in php

I have these value stored in a decimal 10,2 field

1052730
956700

How do i print this using php so that the value is like

$10,527.30
$9,567.00

basically i am trying to avoid the value as

$1,052,730 <--- this i dont want

You can use the

 money_format($format, $value)

function in php. The details of the formatting is given here .

Well, assuming that 1052730 is really 10527.30 as alluded to in your question:

$number = 1052730;
$decimals = $number % 100;  //30 in this case
$digits = floor($number / 100);
$paddedDecimals = str_pad($digits, 2, '0', STR_PAD_LEFT);
$out = '$' . number_format($digits, 0).'.'.$paddedDecimals;
echo $out; // $10,527.30

There are no floating point calculations used for the decimal part, so there's no need to worry about precision issues (although at this precision it would likely be hard to get a float error in there)...

Just divide by 100:

<?php

echo number_format(1052730/100, 2, '.', ',') . PHP_EOL;
echo number_format(956700/100, 2, '.', ',') . PHP_EOL;
printf ("$%01.2f", ($input / 100));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM