Log in

View Full Version : Force values to two decimal places



jjz
06-16-2011, 08:02 AM
I am a very raw beginner. I have the code

printf('%01.2f', $total);

but I don't know where to put it. I have a print statement:

print (
<p>
Total<br />
' . $total . '
</p>
);

I suppose I change print to printf, is that right? and where do I put the print('#01.2f', $total);

This probably sounds totally confused but if someone could help sort me out I'd be very grateful.

jjz
06-18-2011, 12:50 PM
Anyone have a suggestion as to where I might go to find an answer or some help towards finding an answer?

bluewalrus
06-18-2011, 01:32 PM
<p>
Total
<?php
//$total = 1234.93265; for testing
$total = sprintf('%01.2f', $total);
echo $total;
?>
</p>

This usage auto rounds, you could use regex to limit it to the single 2 values.


<p>
Total
<?php
$dec = '';
//$total = '123451234.913412341'; for testing
if (preg_match('/.*\.(\d\d).*/', $total)) {
$dec = '.' . preg_replace('/.*\.(\d\d).*/', '$1', $total);
$total = preg_replace('/(.*)\.\d\d.*/', '$1', $total);
}
echo $total . $dec;
?>
</p>

fastsol1
06-18-2011, 06:25 PM
Are you trying to display a price with 2 decimal places? If so then you can use the number_format()

number_format($total, 2);

djr33
06-19-2011, 12:26 AM
I think you could also just use round(). I'm not sure how it differs from number_format() though. Maybe number format can handle more complicated things.

round($number,2);

Then you can use echo (with anything) to display it. Or print().


echo $variable;
echo round($number,2);

jjz
06-19-2011, 07:29 AM
Thank you so much bluewalrus, fastsol1 and djr33. I'll give them all a try and see if I can get something to work. :)