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

See, I want to write a function that takes a floating-point parameter and rounds the float to the nearest currency value (float with two decimal places), but if the float parameter has a zero fraction (that is, all zeros are behind the decimal place), then it returns float as an integer (or, i.e., truncates the decimal part, since all zeros are all the same.).

However, I found that I can’t understand how to determine if a fraction has a zero fraction. I do not know if there is a PHP function that already does this. I watched. The best I can think of is to convert a floating-point number to an integer by setting it first, and then subtract the integer part from the float, and then check if the difference is zero or not.

+4
source share
5 answers
if($value == round($value)) { //no decimal, go ahead and truncate. } 

This example compares the value with itself, rounded to 0 decimal places. If the rounded value matches the value, you do not have a decimal. Simple and simple.

+11
source

A small trick with PHP type manipulation capabilities

 if ($a == (int) $a) { // $a has a zero fraction value } 
+8
source
 function whatyouneed($number) { $decimals = 2; printf("%.".($number == (int)($number) ? '0' : $decimals)."F", $number); } 

So basically it is either printf("%.2F") if you want 2 decimal places and printf("%.2F") if you don't want it.

+1
source

Well, the problem is that the floats are not accurate. Read here if you are interested to know why. What I would like to do is to solve the level of accuracy, for example, 3 decimal places and basic accuracy. To do this, you multiply it by 1000, pass it to int and then check if $ your_number% 1000 == 0 is equal.

 $mynumber = round($mynumber *1000); if ($mynumber % 1000==0) { isInt() } 
0
source

Just so that you know, you do not need to write a function to do this, there already exists one that exists:

 $roundedFloat = (float)number_format("1234.1264", 2, ".", ""); // 1234.13 

If you want to keep the trailing .00 , just omit the float tide (although it will return a string):

 $roundedFloatStr = number_format("1234.000", 2, ".", ""); // 1234.00 
0
source

All Articles