party party - 7 months ago 12
PHP Question

How to add another digit to the results of a json decode?

I have a ticker on the top of my website.

Right now the results display

2.14


The api I'm calling gives me an extra digit but its not displaying.

The results should be displaying
2.147


Here's some of the code I'm working with.

$obj = json_decode($json);
$symbol[$i] = $obj->results[0]->symbol;
$open[$i] = number_format($obj->results[1]->open, 2, '.', ',');
$high[$i] = number_format($obj->results[1]->high, 2, '.', ',');
$low[$i] = number_format($obj->results[1]->low, 2, '.', ',');
$close[$i] = number_format($obj->results[1]->close, 2, '.', ',');
$gap[$i] = number_format($obj->results[1]->close - $obj->results[0]->close, 2, '.', ',');
$percent[$i] = number_format($obj->results[1]->close / $obj->results[0]->close, 2, '.', ',');


How can I make the ticker display the third digit after the decimal?

Answer

Replace all the 2 values (which represent 2 decimal places) to 3 (which is the 3 decimal places that you want).

Basically the second attribute show's the number of decimal places you'd like to format your result to.

Here are the docs: http://php.net/manual/en/function.number-format.php

This is what your code should look like:

$obj = json_decode($json);
$symbol[$i] = $obj->results[0]->symbol;
$open[$i] = number_format($obj->results[1]->open, 3, '.', ',');
$high[$i] = number_format($obj->results[1]->high, 3, '.', ',');
$low[$i] = number_format($obj->results[1]->low, 3, '.', ',');
$close[$i] = number_format($obj->results[1]->close, 3, '.', ',');
$gap[$i] = number_format($obj->results[1]->close - $obj->results[0]->close, 3, '.', ',');
$percent[$i] = number_format($obj->results[1]->close / $obj->results[0]->close, 3, '.', ',');
Comments