0

Why is this outputting 0.99 and not 1?

<?php
    echo bcmul("2.54", "0.3937007874015748", 2);    // 0.99
    echo 2.54 * 0.3937007874015748;    // 1
?>

My PHP Version 7.4.33

3
  • Because that's what it is? Why would you expect 1? You're not asking to round anything. Try it with 20 for the 3rd arg and you get 0.99999999999999999200. Commented Jul 3, 2024 at 17:46
  • 3
    The actual result of your multiplication is 0.999999999999999992000000000000...... and so on. If you ask for only 2 decimals you get 0.99. The real question is why you get 1 when you use echo 2.54 * 0.3937007874015748;. PHP uses the IEEE 754 double precision format for floats, which can compute with a precision of just under 16 digits. Your computation requires a precision of 17 digits, one digit more than the format provides, so the result is rounded. Commented Jul 3, 2024 at 18:16
  • It isn't explicitly mentioned in the manual (not at least in bcmul() page) but the $scale parameter is just the number of decimals to process. It doesn't imply there's a rounding feature implemented around it: 3v4l.org/1j6FH#v8.3.9 Commented Jul 4, 2024 at 7:07

1 Answer 1

0
bcmul("2.54", "0.3937007874015748", 2); // with scale 2, '2.54' * '0.39' = '0.99'

It's like calculating to N decimal places using a pen and paper with your hands.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.