I use Laravel with vue/vuetify in frontend.
In a simple form, the user can set the settlement_factor
which is a number with 2 decimals.
The field in the DB looks like
If I enter 1.68 the entry in the db is 1.68 but the system returns 1.68000000000002
Patch request value:
"settlement_factor": "1.68",
Response value
"settlement_factor": 1.6800000000000002,
But if I enter 1.67, the system returns 1.67 which is right:
Patch request value:
"settlement_factor": "1.67",
Response value
"settlement_factor": 1.67,
I use Laravel ressources to modify the response:
'settlement_factor' => $this->settlement_factor,
Why does the system change the value 1.68 to 1.68000000000002 but the other numbers are ok?
I have no Idea to find the error.
For a quick fix, I can add the round()
function.
CodePudding user response:
Don't use double for this. Double is a floating point number encoded in 64 bits. The encoding of a decimal number in binary cannot always be exact. 1.68 happens to be one of the numbers where the encoding is not exact so you see it displayed as 1.68000000000002.
Use Decimal (5,2) this would allow for 5 significant digits with 2 to the right of the decimal point. This would give you a range of 0 to 999.99. You can adjust these 2 number to fit the range you expect for the number. To match to the number you used, use Decimal (3,2) which gives you a range of 0.00 to 9.99.
Rounding will be managed by Decimal Type so you will not see the encoding deviation like in Double.