-2

I have a double, that is being read in by an XML document, with 7 digits after the decimal place.

I want to get it to 4, but nothing seems to be working, number format and round used, My final idea was *1000, format /1000 but its not using the numbers in the decimal place.

echo $lng;
$lng = $lng * 1000;
echo $lng;
$lng = number_format($lng,0);
echo $lng;
$lng = $lng / 1000;
echo $lng;

This gives me the following results:

lng -2.9763323 
lng -2000 
lng -2,000 
lng -0.002 

Any help would be welcome

Craig Weston
  • 141
  • 2
  • 4
  • 10
  • What is the format you expect? That will go a long way enable the community assist you effectively. In any case, you question is strongly related to [this one](https://stackoverflow.com/questions/4483540/php-show-a-number-to-2-decimal-places). Other reference: `number_format(number,decimals,decimalpoint,separator)`. You may consider checking [w3schools.com](http://www.w3schools.com/php/func_string_number_format.asp) as well. – nyedidikeke Sep 09 '16 at 13:20
  • Also, [PHP.net](https://secure.php.net/manual/en/function.round.php). – nyedidikeke Sep 09 '16 at 13:26

3 Answers3

0

If you want to get it to 4 decimal places using this method, you will need to multiply by 10,000 and not 1,000. Try this instead:

$lng = -2.9763323;

echo intval($lng * 10000) / 10000; // outputs: -2.9763

round would probably be better to use, though, as it is simpler to understand and is exactly what this is meant for:

echo round($lng, 4); // outputs: -2.9763

Plus it can give you the option do other modes of rounding rather than just a simple floor, such as round half up/down, and round half even/odd. In the example case, you would get the same output no matter what rounding mode you chose since the difference is only when the last digit in the desired precision is followed by a 5.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
0

use round() EG. echo round(10.12456789, 4);

Arun Karnawat
  • 575
  • 10
  • 21
0

Not sure what you meant by round isn't working, but:

$lng=round($lng,4);
echo $lng;

produces -2.9763 for me. Did you want it to have 4 digits total?

code11
  • 1,986
  • 5
  • 29
  • 37