开发者

Removing all decimals in PHP

get this from my database:

252.587254564

Well i wanna remove the .587254564 and keep the 252, how can i do that?

What function should i use and can开发者_Go百科 you show me an example?

Greetings


You can do it in PHP:

round($val, 0);

or in your MYSQL statement:

select round(foo_value, 0) value from foo


You can do a simply cast to int.

$var = 252.587254564;
$var = (int)$var; // 252


As Tricker mentioned you can round the value down or you can just cast it to int like so:

$variable = 252.587254564; // this is of type double
$variable = (int)$variable; // this will cast the type from double to int causing it to strip the floating point.


In PHP you would use:

$value = floor($value);

floor: Returns the next lowest integer value by rounding the value down if necessary.

If you wanted to round up it would be:

$value = ceil($value);

ceil: Returns the next highest integer value by rounding the value up if necessary.


You can just cast it to an int:

$new = (int)$old;


Convert the float number to string, and use intval to convert it to integer will give you 1990

intval(("19.90"*100).'')


Before using above answer what is your exact requirement please see bellow example output.

$val = 252.587254564;

echo (int)$val; //252
echo round($val, 0); //253
echo ceil($val); //253


$val = 1234567890123456789.512345;

echo (int)$val; //1234567890123456768
echo round($val, 0);//1.2345678901235E+18
echo ceil($val); //1.2345678901235E+18


$val = 123456789012345678912.512345;

echo (int)$val; //-5670419503621177344
echo round($val, 0);//1.2345678901235E+20
echo ceil($val); //1.2345678901235E+20


you can use echo (int) 252.587254564;


positive number:

round(252.587254564) // 253
floor(252.587254564) // 252
ceil(252.587254564) //252
(int)252.587254564 // 252
intval(252.587254564) // 252
~~252.587254564 // 252

negative number:

round(-252.587254564) // -253
floor(-252.587254564) // -253
ceil(-252.587254564) // -252
(int)-252.587254564 // -252
intval(-252.587254564) // -252
~~-252.587254564 // -252

if you want just remove decimals without round you can use one of above codes except round and floor(for negative number).

But I recommended the last one, it's simpler and faster using prefix ~~


And there is also a not quite advisable method:

strtok($value, ".");

This cuts of the first part until it encounters a dot. The result will be a string, not a PHP integer. While it doesn't affect using the result much, it's not the best option.


I see many answers, but the question is:

"Well i wanna remove the .587254564 and keep the 252, how can i do that?"

Since the questioner is asking for php, the function in php will be the one for the job.

$newValue = floor($value);


In MySQL you can use:

select floor(field)

or in PHP you can use:

floor($value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜