Elvis Reis
Elvis Reis

Reputation: 305

Error in php when converting a float to integer

When I do a conversion from a float number to integer it behaves strangely and does not have the expected result

<?php
$amount = str_replace(",", "", '1,051.36') * 100; //105136
$number = (int)$amount; //105135

Upvotes: 0

Views: 69

Answers (2)

Md. Rezwanul Haque
Md. Rezwanul Haque

Reputation: 2950

You can this way:

<?php
$amount = str_replace(",", "", '1,051.36') * 100; //105136
$number = (int)ceil($amount); //105136

Upvotes: 0

devman
devman

Reputation: 31

You can use round(), floor() or ceil() functions to round your amount float to the closest integer.

// round to next highest Int 
$number_ceiled = ceil($amount); //105136

// round to next lowest Int 
$number_floored = floor($amount); //105135

// can do both and round to the much closed 
$number_rounded = round($amount); //105136

return (int)$number_rounded; //105136

Consider espacially round() in your case.

Here are the docs :

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

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

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

Cheers,

Upvotes: 1

Related Questions