2

I have an issue with laravel or php (don´t know yet), the issue is the next:

I have a field on my database called debe which value is 3.97 as you can see below. This field is a double(11,2).

sql table row

When I access to that field on my framework, for example using a dd() it returns the value correctly as you can see below.

dd result

The main problem occurs when i'm trying to print into the view, I receive the next:

value printed

I dont know why this is happening but right now the only solution that I've found is to round the value using PHP round() function.

Regards

8
  • 3
    Could you post your code? And Your question is why the dd output is collection? Commented Oct 18, 2019 at 8:35
  • 1
    how about using number_format ? Commented Oct 18, 2019 at 8:36
  • 1
    @lighter My question is why php or laravel is formatting the field, the field in the database is 3.97 and the question is why I get 3.96999999998 and no 3.97 Commented Oct 18, 2019 at 8:41
  • 1
    The problem is just number's Precision. Commented Oct 18, 2019 at 8:43
  • 2
    check stackoverflow.com/questions/6503994/… Commented Oct 18, 2019 at 8:48

1 Answer 1

3

Check this article in the official documentation:

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

You can use the round or number_format functions to get the desired decimals

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

1 Comment

Thanks for the answer, I read the documentation and I am agree, but one more question... Does it happen randomly?? cause for example 3.98 gets printed well...

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.