Ben
Ben

Reputation: 175

PHP, Prevent from removing leading zeros

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

Upvotes: 4

Views: 2465

Answers (7)

Piskvor left the building
Piskvor left the building

Reputation: 92762

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.

Upvotes: 9

badideas
badideas

Reputation: 3557

convert to metric

Upvotes: 3

jkndrkn
jkndrkn

Reputation: 4062

When using non-decimal units such as feet and inches or time, I like to use the smallest unit I'm interested in (seconds or inches) to track values internally and then convert to feet and inches for output purposes. I think you'll find this easier than to try to adapt decimal numbers for this purpose.

Upvotes: 5

soulmerge
soulmerge

Reputation: 75714

These values are converted to floats implicitely somewhere in your code. You need to find that line and rewrite it to keep the string type. Do you use these values in mathematical expressions, for example?

Upvotes: 0

Satanicpuppy
Satanicpuppy

Reputation: 1587

Yea, it's Settype

settype($bar, "string");  // $bar is now "1" (string)

Wait. How is the 0 in 5.10 a leading zero?

I fail at reading comp. printf/sprintf would work better in a case where you are forcing 2 significant figures, regardless of whether the trailing one is a zero.

Upvotes: 0

codaddict
codaddict

Reputation: 455092

You can try using printf

$a = 5.10;

echo $a;            // prints 5.1

printf("%.2f",$a);  // prints 5.10

Upvotes: 0

Tyler Carter
Tyler Carter

Reputation: 61567

You could cast it manually using printf() or sprintf()

(Links coming shortly)

Upvotes: 0

Related Questions