如何在PHP中去除尾随零 [英] How to strip trailing zeros in PHP

查看:44
本文介绍了如何在PHP中去除尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我一个解释(也许是一个例子),我将如何使用PHP从数字中去除尾随零.

Hi could anyone give me an explanation (and maybe an example) as to how would I go about stripping the trailing zeros from a number using PHP.

例如:

"Lat":"37.422005000000000000000000000000","Lon":"-122.84095000000000000000000000000"

将转到:

"Lat":"37.422005","Lon":"-122.84095"

我正在尝试去除零,以使其更具可读性.我尝试使用str_replace(),但这也替换了数字中的零(doh).

I am trying to strip the zeros to make it more readable. I tried using str_replace() but this replaced the zeros inside the number too (doh).

谢谢= D

推荐答案

忘记所有的rtrim和正则表达式,坐标是浮点数,应将其视为浮点数,只需在变量前加上(float)即可将其从字符串中强制转换浮动:

Forget all the rtrims, and regular expressions, coordinates are floats and should be treated as floats, just prepend the variable with (float) to cast it from a string to a float:

$string = "37.422005000000000000000000000000";
echo (float)$string;

输出:

37.422005

实际的结果是浮点数,但是由于HTTP协议而作为字符串传递给您,最好将它们转换回自然形式以进行计算等.

The actual result you have are floats but passed to you as strings due to the HTTP Protocol, it's good to turn them back into thier natural form to do calculations etc on.

测试用例: http://codepad.org/TVb2Xyy3

注意:关于PHP中浮点精度的评论,请参见: https://stackoverflow .com/a/3726761/353790

Note: Regarding the comment about floating point precision in PHP, see this: https://stackoverflow.com/a/3726761/353790

这篇关于如何在PHP中去除尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆