4

Given this PHP code:

// total is 71.24 (float)
$value = $total * 100;
var_dump($value);
$valuecast = (int)$value;
var_dump($valuecast);
settype($value, 'int');
var_dump($value);

var_dump($value) gives float(7124)

var_dump($valuecast) gives int(7123)

var_dump($value) after settype gives int(7123)

How can I get the correct type conversion?

0

2 Answers 2

4

From PHP Manual on TypeCasting Float to Integer

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
    echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision.

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

1 Comment

The de3 link doesn't seem to be online anymore. So try php.net/manual/en/language.types.float.php#warn.float-precision
2

For float to int, I'd suggest round. This is to cater to IEEE float imprecision.

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.