sajith
sajith

Reputation: 2702

How to convert float value to integer in php?

I want to convert float value (Eg:1.0000124668092E+14) to Integer in php,what is the best method for this in php.output should be "100001246680920"

Upvotes: 69

Views: 209554

Answers (6)

Waids
Waids

Reputation: 118

Try this

<?php
$float_val = 1.0000124668092E+14;
 echo intval($float_val);
?>

Upvotes: 8

William Desportes
William Desportes

Reputation: 1711

I just want to WARN you about:

>>> (int) (290.15 * 100);
=> 29014
>>> (int) round((290.15 * 100), 0);
=> 29015

Upvotes: 49

JamLizzy101
JamLizzy101

Reputation: 165

There is always intval() - Not sure if this is what you were looking for...

example: -

$floatValue = 4.5;
echo intval($floatValue);    // Returns 4

It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.

Here is some documentation for this: - http://php.net/manual/en/function.intval.php

Upvotes: 8

fullybaked
fullybaked

Reputation: 4127

Use round, floor or ceil methods to round it to the closest integer, along with intval() which is limited.

http://php.net/manual/en/function.round.php

http://php.net/manual/en/function.ceil.php

http://php.net/manual/en/function.floor.php

Upvotes: 3

pozs
pozs

Reputation: 36244

What do you mean by converting?

  • casting*: (int) $float or intval($float)
  • truncating: floor($float) (down) or ceil($float) (up)
  • rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants

*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.

PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).

But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)

Upvotes: 82

Mr. Alien
Mr. Alien

Reputation: 157334

Use round()

$float_val = 4.5;

echo round($float_val);

You can also set param for precision and rounding mode, for more info

Update (According to your updated question):

$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201

Upvotes: 17

Related Questions