Kiren S
Kiren S

Reputation: 3097

Rendering whole numbers as floats in PHP JSON response

I am passing JSON response as below in PHP webservice (Lumen)

$obj = ['test' => 0.0 ];
return $res = json_encode($obj);

But its response is casted to integer. See below

{"test":0}

I am expecting it as floating point number 0.0 (not a string) in the response.

Upvotes: 0

Views: 1206

Answers (1)

Samuil Banti
Samuil Banti

Reputation: 1795

Values such 0.0, 1.0 and so on are whole numbers there's nothing wrong in this case.

But if you insist to keep the type of the variable you may do it like this:

json_encode($obj, JSON_PRESERVE_ZERO_FRACTION);

Upvotes: 7

Related Questions