Support the ongoing development of Laravel.io →
Configuration Database Eloquent

Hi guys, on one of my site that i've builded with laravel 4.1, i've something strange with select data fetched from DB. I've some float value, like 426.98. So, now when i tried to fetch i have like some rounding around this value and it changed in 430. But i'm not using some rounding function on fetch data So why this happened ?

Last updated 3 years ago.
0

Is there a particular reason that you are using a float, for scientific calculations perhaps?

If you want to store financial/monetary values I would recommend that you use decimal.

Also, how did you declare your float?

If you are working to 2 decimal places (common for monetary values), if you insist on using floats then declare it like this:

float(15,2)

where 15 is the total length of the value including decimal places and 2 is the number of digits after the decimal point. Again I would recommend:

decimal(15,2).

To display the data after any calculations, I would use number_format():

$someValue = 426.98 * 3.333333;

echo $someValue; // 1423.26652434

$myCalculatedValue = number_format($someValue, 2, '.', '');

echo $myCalculatedValue; // 1423.27

http://php.net/manual/en/function.number-format.php

Hope this is some help.

EDIT:

I might add that if you are calculating exchange rates or share prices for example, you will need more than 2 decimal places, otherwise your calculations will be way out particularly as the amount increases.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.