I'm trying to format a decimal number that I've optained from a json object in PHP. My objective is to keep this number with just two places after the comma.
Here is the code:
`
$url = "https://api.yadio.io/exrates/EUR";
$data = json_decode(file_get_contents($url, true));
$object = $data;
foreach($object as $a){
echo round($a->CUP, 2);
}
`
The result without round()
was 163.905765
, so when I apply it, the result is 0163.9100
and should be 163.90
.
Any help will be very appretiate.
CodePudding user response:
Your json response is of type -
{
"BTC": 20849.71,
"EUR": {
"CAD": 1.353201,
"CDF": 2030.444751,
"CHF": 0.990328,
"CLP": 939.150233,
"CNY": 7.204403,
"COP": 4731.844098,
"CRC": 617.225833,
"CUP": 163.905765,
},
"base": "EUR",
"timestamp": 1666977603763
}
So you are not looping around it correctly.
try this -
$url = "https://api.yadio.io/exrates/EUR";
$data = json_decode(file_get_contents($url, true));
$object = $data;
echo round($object->EUR->CUP,2);