Convert strings to numbers without losing decimals

2019-08-15 06:29发布

I'm developing a map and I have to save this parameters on Parse database:

lat.: 20.6350 . Long: -103.5334

The problem is when i convert them into numbers, that function converts 20.6350 to 20.635. ¿What can I do in order tu preserve the last zero?

2条回答
Deceive 欺骗
2楼-- · 2019-08-15 07:06

if you want the numbers with four decimals in your database you could use the Decimal type. Under length you could enter 6,4 representing maximum of 6 digits in total and 4 digits behind the point.

If you want to display the number in PHP you could use the number_format() function

echo number_format($longitude, 4);
查看更多
你好瞎i
3楼-- · 2019-08-15 07:17

You should specify the sig figs and they will display properly.

$lat = "20.6350";
$lng = "-103.5334";

print number_format($lat, 4); // 4 sig figs
print number_format($lng, 4);

See http://php.net/number_format for additional formatting info

UPDATE

Based on your comments above, seems the string you're pulling varies in length, correct?

Why not just get the amount of sig figs after the decimal then use that as the second argument in number_format()? I'm sure there is a more appropriate way to handle, but this would work I believe.

// Calculate sig figs
$length = strlen($lng) - (stripos($lng, '.') + 1);
number_format($lng, $length);

or in one line

number_format($lng, strlen($lng) - (stripos($lng, '.') + 1));
查看更多
登录 后发表回答