Errol Fitzgerald
Errol Fitzgerald

Reputation: 3008

Subtracting close together numbers in php

Why does

<?php echo 194.95-194.94; ?>

output

0.0099999999999909

What am i missing here? This is php 5.2.

Upvotes: 2

Views: 735

Answers (2)

Ray Toal
Ray Toal

Reputation: 88408

While Mark's answer is okay, it may still leave you wondering why you got the answer you did. For example, try

<?php echo 0.01; ?>

PHP happily prints 0.01.

In your case 194.95 and 194.94 were both stored in as-close-a-binary-form as could be accommodated in IEEE 754, and their difference was too far away from the basic 0.01 that could be rendered "properly".

Try out your example on an online calcuator such as http://babbage.cs.qc.edu/IEEE-754/Decimal.html. Should be interesting.

Upvotes: 3

Mark Elliot
Mark Elliot

Reputation: 77064

The issue is that you cannot represent 0.01 exactly in floating point.

Have a look at what every programmer should know about floating point for a great explanation of why this is, and what to do about it.

Upvotes: 10

Related Questions