Format number with decimals without rounding

Description:

Trying to get a precise number of decimal in a number results most of the times in a rounding of the number. Both round() and number_format() functions of PhP round the output result.

Solution:

The solution to this issue is to multiply the number by the power of 10 that is the number of decimals. 10 for 1 digit, 100 for 2 digits and so on.

$originalNumber = 150.8699; //we want to obtain 150.86
$multipliedNumber = originalNumber * 100; //output is 15086.99

Then, we apply the floor() function, to get rid of the additional trailing decimals:

$integerMultipliedNumber = floor($multipliedNumber); //output is 15086

Finally, divide the number back to the decimal power of 10 (100 in our case) and parse it as a float:

$twoDecimalResult = (float) ($integerMultipliedNumber / 100); //output is 150.86

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in Best practices, PhP and tagged , , , . Bookmark the permalink.

2 Responses to Format number with decimals without rounding

  1. Alex says:

    Thanks for sharing man, this solved one issue for me, I hope 🙂

  2. Sunil says:

    Its working fine in some cases but not for all, I need 5 digit after decimal point means want same result id my number is of 5 digit after decimal. But I get 5.02074
    $number = 5.02075;
    echo floor($number * 100000) / 100000;
    It return wrong result
    5.02074

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s