MKroeders
MKroeders

Reputation: 7752

Float to int error

Yesterday I was helping some one and got a weird error which I could not explain to him how it worked.

The code (tested on 3 machines (PHP 5.3 and PHP 5.4))

// (float)65.35
$percentage = round(65.351, 2);
// (float) 6535
$total = $percentage * 100;
// (int) 6534
$int = (int) $total;

What is suspected was that the int value would be 6535 but it ended up being 6534.

Could some one explain what is going on?

Upvotes: 2

Views: 416

Answers (4)

Restie
Restie

Reputation: 53

$r=$explode('.',$total);
debug($r);

Upvotes: 0

nl-x
nl-x

Reputation: 11832

This has to do with how floating point (read the warning in this link!) values are stored in memory. Indeed after the first operation you don't have an exact decimal value, but a rounded value. Probably 65.34999999 or so. (The value is stored as a list of bits (0/1))

This is why when talking about money, developers don't store dollars/euros but rather the amount of cents. This way they avoid working with floats that are less precise for decimals, but rather work with integers, that are precise.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798556

You don't actually have 65.35 after the first operation.

>>> '%.20f' % (65.351 - 0.001,)
'65.34999999999999431566'

Either start with an integral value scaled appropriately in the first place, don't attempt to convert the value to an integer, or add a small value before taking the integer value.

Upvotes: 5

Sahil Mittal
Sahil Mittal

Reputation: 20753

Use round instead of int

round($total)

Upvotes: 2

Related Questions