Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I truncate a decimal in PHP?

Tags:

php

truncate

I know of the PHP function floor() but that doesn't work how I want it to in negative numbers.

This is how floor works

floor( 1234.567); //  1234
floor(-1234.567); // -1235

This is what I WANT

truncate( 1234.567); //  1234
truncate(-1234.567); // -1234

Is there a PHP function that will return -1234?

I know I could do this but I'm hoping for a single built-in function

$num = -1234.567;
echo $num >= 0 ? floor($num) : ceil($num);
like image 428
chrislondon Avatar asked Jun 29 '13 19:06

chrislondon


2 Answers

Yes intval

intval(1234.567);
intval(-1234.567);
like image 57
Manoj Yadav Avatar answered Sep 23 '22 17:09

Manoj Yadav


Truncate floats with specific precision:

echo bcdiv(2.56789, 1, 1);  // 2.5
echo bcdiv(2.56789, 1, 3);  // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 3); // -2.567

This method solve the problem with round() function.

like image 44
pablorsk Avatar answered Sep 22 '22 17:09

pablorsk