i receive some data including a decimal number from an api in post request with content-type:json
among the posted data , is a Amount
parameters with 4 decimal places
{
"Amount": 500.0000 ,
"param1" : "value1" ,
"param2" : "value2"
}
after parsing the json
$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);
here is my output
array(3) {
["Amount"]=>
float(500)
["param1"]=>
string(6) "value1"
["param2"]=>
string(6) "value2"
}
the problem is im losing the decimal places on the Amount if they are zero
so instead of 500.0000
i get 500
, i know they are the same numbers mathematically but i need to generate a hash from these posted parameters which requires me to have Amount
as a float number with 4 decimal places exactly as posted in the first place
i can do something like
$data['Amount'] = sprintf('%0.4f', $data['Amount'] );
but than it would convert the Amount into an string , which results in a invalid hash
array(3) {
["Amount"]=>
string(8) "500.0000"
["param1"]=>
string(6) "value1"
["param2"]=>
string(6) "value2"
}
i need my $data output to be
["Amount"]=>
float(500.0000)
tried to run it throw floatval , lost the decimal zeros again ! im losing my mind over something so simple , any idea how to solve this ?
CodePudding user response:
In C#, you can do this with the decimal
type instead of double
or float
. While my PHP knowledge is limited, it looks like the PHP world has something similar in BC Math and PHP Decimal.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types https://www.php.net/manual/en/book.bc.php https://php-decimal.io/
CodePudding user response:
Use built-in number_format function.