开发者

PHP, Prevent from removing leading zeros

I开发者_如何学Python 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


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.


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.


convert to metric


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

(Links coming shortly)


You can try using printf

$a = 5.10;

echo $a;            // prints 5.1

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


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜