0

Given the following cod:

 $number = 1050.55;
 var_dump($number - floor($number));

Why does the above code returns the following result?

float(0.54999999999995)

I want a fixed value like 0.55 in this case. Can you help me please?

Jorge Zapata
  • 2,316
  • 1
  • 30
  • 57

3 Answers3

3

Floating point operations are not precise and the remainder errors are common. If you know, what is your desired precission (eg. two digits after the dot), you can use round() function on the result. In this case this will be:

$number = 1050.55;
var_dump(round($number - floor($number), 2));
Tomasz Struczyński
  • 3,273
  • 23
  • 28
2

For most floats, binary can only approximately represent the correct number. The rule is to perform floor(), ceil() or fmod() last in a series of calculations. At least only do integer math after you use them. If you cast an int to a float, as in your code, then floor() is not going to behave has you expect.

Use printf() when printing floats. Its conversion routines usually do a much better job and give you the answer you expect when truncating floats.

EDIT: Or, to be more exact, printf() works on the decimal character representation of the number when deciding where to truncate so you don't get any weird, unspecified, binary/decimal conversion artifacts.

starbolin
  • 840
  • 5
  • 13
1

See this question. While that is about java and you're asking about PHP the math is the same.

Community
  • 1
  • 1
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102