Ensuring a number is in decimal format

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hame22
Forum Contributor
Posts: 214
Joined: Wed May 11, 2005 5:50 am

Ensuring a number is in decimal format

Post by hame22 »

I have a variable $tax_price that I need to ensure is always in a decimal format; 0.00 (2 decimal places)

I have noticed the printf function for display puurposes, is there a function that can be used to ensure a number is placed into a specified decimal format?

thanks in adavnce
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

From the PHP manual for

Code: Select all

round()
To round any number to a given number of significant digits, use log10 to find out its magnitude:

round($n, ceil(0 - log10($n)) + $sigdigits);

Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:

// $exp = currency decimal places - 0 for Yen/Won, 2 for most others
$dp = ceil(0 - log10($n)) + $sigdigits;
$display = number_format($amount, ($exp>$dp)?$exp:$dp);

This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Post Reply