Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the best way to detect if a float has a zero fraction value (e.g. 125.00) in PHP?

Tags:

function

php

math

See, I want to write a function that takes a float number parameter and rounds the float to the nearest currency value (a float with two decimal places) but if the float parameter has a zero fraction (that is, all zeroes behind the decimal place) then it returns the float as an integer (or i.e. truncates the decimal part since they're all zeroes anyways.).

However, I'm finding that I can't figure out how to determine if if a fraction has a zero fraction. I don't know if there's a PHP function that already does this. I've looked. The best I can think of is to convert the float number into an integer by casting it first and then subtract the integer part from the float and then check if the difference equals to zero or not.

like image 456
racl101 Avatar asked Nov 23 '10 22:11

racl101


2 Answers

if($value == round($value))
{
    //no decimal, go ahead and truncate.
}

This example compares the value to itself, rounded to 0 decimal places. If the value rounded is the same as the value, you've got no decimal fraction. Plain and simple.

like image 100
Surreal Dreams Avatar answered Oct 21 '22 06:10

Surreal Dreams


A little trick with PHPs type juggling abilities

if ($a == (int) $a) {
    // $a has a zero fraction value
}
like image 37
KingCrunch Avatar answered Oct 21 '22 05:10

KingCrunch