0
1.15 * 100              // 115 correct
(int)(1.15 * 100)       // 114 incorrect
intval(1.15 * 100)      // 114 incorrect

floor(1.15 * 100)       // 114 incorrect
floor(1.1501 * 100)     // 115 correct

I try to cut off the fractional part after the 2nd character and translate it into an integer. It turns out with an error. Tell me how to correctly translate.

Takamura
  • 302
  • 1
  • 4
  • 16
  • The result is the same in version `7.1.1`, `5.4.36` and `5.6.2`. – Raptor Dec 21 '17 at 01:50
  • This isn't a php 7 question, yet alone 7.1. RTM's http://php.net/manual/en/function.floor.php --- http://php.net/manual/en/function.intval.php – Funk Forty Niner Dec 21 '17 at 01:51
  • 2
    As mentioned in `intval()` function documentation's comment, you can first use `strval()`, then use `intval()`, e.g. `intval(strval(1.15 * 100))` which gives you correct results. – Raptor Dec 21 '17 at 01:57
  • you could also use the number_format function with zero decimals `(int)number_format((1.15 * 100),0)` or cast it first into a string `(int)(string)(1.15 * 100)` – knetsi Dec 21 '17 at 02:00
  • @Raptor You beat me to posting my answer. I added your single line as an alternative. – Bradmage Dec 21 '17 at 02:04
  • 3
    `1.15` can't be represented exactly in floating point, it's actually something like `1.1499999999999923`. That's why you get the result you see. Use `round()` instead of `floor()` to mitigate problems like this. – Barmar Dec 21 '17 at 02:29

1 Answers1

1

var_dump( 1.15 * 100 ); outputs a float - unmodified.

var_dump( (int)(1.15 * 100) ); outputs an int - the float above converted to an int, which does rounding even for seemingly the same number.

$var1 = (string)(1.15 * 100);
var_dump( (int)($var1) );

You would need to convert the float to a string first, then to an int.

Edit: Or a single line answer: intval(strval(1.15 * 100))

Bradmage
  • 1,233
  • 1
  • 15
  • 41