Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Prevent from removing leading zeros

Tags:

php

math

I have an array of numbers from 5 to 6.4 but the numbers are relating to feet and inches and I am using them for calculation.

When I come to use 5.10 it removes the zero and I have the same output as though it was 5.1.

Is there anyway to prevent PHP removing the 0. I presume it does some sort of default casting.

Thanks in advance

like image 823
Ben Avatar asked Dec 04 '22 13:12

Ben


1 Answers

If you mean "5 feet and 10 inches", you can't represent that with an integer (or float) - as you see, you'll run into major problems this way.

The computer is doing exactly what you asked from it (not necessarily what you intended). E.g. Google tells me that 5.8 feet == 69.6 inches, which is slightly more than 5 feet 8 inches (== 68 inches). However, (float) 5.10 === (float) 5.1 === (float) 5.100000 (five plus one tenth).

For the US measuring system, you will need something more complicated than an int - as feet and inches are not cleanly convertible to each other in decimal (IIRC, 1 foot = 12 inches, therefore 5 feet 1 inch = 5.083 feet, plus rounding error).

Check out e.g. Zend_Measure; it's a collection of PHP classes which allows you to work with different measuring standards, I think there's support for the US/Imperial system too.

EDIT: if everything else fails, you could convert both numbers to inches - e.g. 5'10" == (5*12) + 10 == 70 inches, which is a nice integer you can work with.

like image 70
Piskvor left the building Avatar answered Dec 06 '22 03:12

Piskvor left the building