0

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
6
  • 1
    Define strange. Commented Jul 21, 2017 at 16:54
  • Floats are weird. Try rounding your float to 2 before you multiply it by 100. Commented Jul 21, 2017 at 16:56
  • its casted to integer. you can examine thorough is is_int($amaount) in if condition. it will return true or false. Commented Jul 21, 2017 at 16:58
  • 1
    try $number = (int)ceil($amount); //105136. This gets around the whole 105135.999999999998 thing. Commented Jul 21, 2017 at 16:59
  • @Dimi +1 you should make an answer out of that with a detailed explanation. Commented Jul 21, 2017 at 17:01

2 Answers 2

1

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,

Sign up to request clarification or add additional context in comments.

Comments

0

You can this way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.