DrRumpus
DrRumpus

Reputation: 59

sprintf rounding

Why does the following produce different results?

echo 2.55 * 100;
echo sprintf(' %d', 2.55 * 100);

output:

255 254

Upvotes: 1

Views: 525

Answers (1)

Álvaro González
Álvaro González

Reputation: 146460

Because 2.55 * 100 in base 2 fixed size representation is not an integer and %d does not round:

var_dump(sprintf('%d', 1.99));
string(1) "1"
ini_set('precision', 20);
var_dump(2.55 * 100);
float(254.99999999999997158)

Unlike printf(), echo $numeric_variable does not have a dedicated mechanism to convert from string to number. It merely casts to string using the default rules, so it's identical to (string)$numeric_variable or strval($numeric_variable). In this case:

  • Since variable type is float it attempts to represent a float (that implies converting from binary IEEE 754 to decimal).
  • It reads the precision directive to fine-tune the representation:

    The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.

To reduce the error in IEEE 754 to decimal conversion, string casting rounds as necessary. In my computer default precision is 14, which is pretty close to the number of nines.

Upvotes: 3

Related Questions