Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert float to int if no decimal part

Tags:

php

i want to convert float to int if there is no decimal part. and if there is decimal part i want to be up to two digits. how do i check if there is a decimal part or not?

so i have data like this.

1.0000
2.0000
3.0000
9.8400
7.3200
8.0000

i want output like this

1
2
3
9.84 round to two digits if there is decimal part
7.32
8

is there a built function in php to know that the float has decimal part or not ? how do i do that in php?

like image 398
professional debugger Avatar asked Dec 06 '25 14:12

professional debugger


1 Answers

I like the printf answer, but you can check if the number is equal to the integer cast of the number:

if( ($int = (int)$number) == $number) {
    $number = $int;
} else {
    $number = round($number, 2);
}

If you actually want 2 decimal places regardless then use number_format.

like image 77
AbraCadaver Avatar answered Dec 09 '25 16:12

AbraCadaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!