How to convert string to number in php without rounding? - php

I am retrieving some values stored as string which have up to 15 decimal places. I need to json_encodeit and pass it on to javascript as numeric value. So I tried (float)$number, but the number gets rounded-off in this approach. How else can I convert it to number without any rounding?

You should use the GMP library in PHP whenever number precision is important. You may have to enable it inside of your php.ini settings. Search for...
;extension=php_gmp.dll
and change it to
extension=php_gmp.dll
and then you'll be able to use the GMP objects.

If you want to preserve those decimals: don't parse it. Any number converted to float is subject to precision loss. Can't you just print the variable as received in JS?

Related

Casting a value into FLOAT in PHP loses the decimal points. Basically turning the value into an INT

I'm calling a PHP form, the float value is received correctly, but if I cast it into a FLOAT, either immediately of afterwards, the value loses all decimal point numbers, and I don't want that. I tried using floatval but same result.
//code
$time_in_seconds = $_POST["time_in_seconds"];//form value is 1.23f
echo $time_in_seconds;//echo 1.23
$time_in_seconds = (float)$time_in_seconds;
echo $time_in_seconds;//echo 1
Install proper locale settings on your machine. Probably you have installed IT (Italy) locale file and there is , as a decimal separator so casting doesn't "see" that you pass it float number.
setlocale(LC_ALL, 'en-US.utf8');
But it's not sufficient to type this line into your code. You must also install locale file.
More info: PHP setlocale has no effect
You are probably using comma and not point to separate decimals.
"1,23" (which will be casted to 1) is different to "1.23" (which will be casted to 1.23)

Representation of small float numbers in json_encode

I'm executing the following code in a PHP script:
$obj = new \stdClass();
$obj->lat = 0.000011399388312455;
echo json_encode($obj) . "\n";
The output of the script is
{"lat":1.1399388312454999446e-5}
As you can see, the number is represented in exponential notation.
Is there some way to represent that particular number in extended notation, in the JSON-serialized object?
The desired output is
{"lat":0.000011399388312455}
The version of PHP is 5.6.30.
P.S.: This JSON-serialized object will be sent to an external web service that doesn't accept numbers in exponential form. Moreover, it needs to be a number and not a string ({"lat":"0.000011399388312455"} won't work).
The number should not be rounded (it's a geographical coordinate).
Here are other similar questions, but they don't fit my case unfortunately.
php- floating point number shown in exponential form
Remove the "E" in a number format for very small numbers
Thank you in advance.
It is implemented in PHP 7.1 https://wiki.php.net/rfc/precise_float_value
As a work around, use other JSON serializers not a default json_encode.
E notation is valid form of float representation. In php >7.1 with precision set to -1 results of your code would look like: {"lat":1.1399388312455e-5} which is absolutely the same as 0.000011399388312455 because you have 4 leading zeros.
If you still want to have leading zeroes in json i would go towards strings. They are perfectly fine for coordinates representations.

Show more digits in PHP

Let's say I have:
echo 1/3;
And it print out only 0.33333333333333, can I get more digits?
Can use bcdiv
echo bcdiv(1, 3, 20);
The third argument
is used to set the number of digits after the decimal place in the result. You can also set the global default scale for all functions by using bcscale().
Edit the precision configuration variable either in your php.ini or some other configuration location or use ini_set().
ini_set('precision', 22);
echo 1/3;
// 0.3333333333333333148296
Even though I highly doubt that you really need that kind of precision ;-)
EDIT
As Gordon said: you'll hit the floating point precision limit in PHP sooner or later (depending on the precision specified). So the better way would be to use either the BCMath Arbitrary Precision Mathematics extension or the GNU Multiple Precision extension, if you're after real high precision mathematics.
You might want tto look into the BC arbitary precision php library
http://php.net/manual/en/book.bc.php
The setting is precision: http://es.php.net/manual/en/ini.core.php
However, I would not use it except for debugging purposes. Have a look at number_format()

php convert floating point to long (convert to string to pass to a xml function)

PHP converts a large number to floating point which I need in "long" format to pass to a soap xml api.
((round(time()/(60*15))*60*15)+(30*60))*1000
This gives the result:
1.28E+12
Whereas, what I need is:
"1280495700000"
in order to pass to the api
format it using number_format()
http://php.net/manual/en/function.number-format.php
This could work:
sprintf('%u',$number);
But if you're about to lose precision you need, look at the BCMath functions (bcadd, bcdiv and the like). They will keep precision, and give you back strings.

Cast a numeric string as float type data

What is the PHP command that does something similar to intval(), but for decimals?
Eg. I have string "33.66" and I want to convert it to decimal value before sending it to MSSQL.
How about floatval()?
$f = floatval("33.66");
You can shave a few nanoseconds off of type conversions by using casting instead of a function call. But this is in the realm of micro-optimization, so don't worry about it unless you do millions of these operations per second.
$f = (float) "33.66";
I also recommend learning how to use sscanf() because sometimes it's the most convenient solution.
list($f) = sscanf("33.66", "%f");
If you mean a float:
$var = floatval("33.66")
Or
$var = (float)"33.66";
If you need the exact precision of a decimal, there is no such type in PHP. There is the Arbitrary Precision Mathematics extension, but it will return strings, so it's only usefull for you when performing calculations.
You could try floatval, but floats are potentially lossy.
You could try running the number through sprintf to get it to a more correct format. The format string %.2f would produce a floating-point-formatted number with two decimal places. Excess places get rounded.
I'm not sure if sprintf will convert the value to a float internally for formatting, so the lossy problem might still exist. That being said, if you're only worrying about two decimal places, you shouldn't need to worry about precision loss.
php is a loosely typed language. It doesn't matter if you have
$x = 33.66;
or
$x = "33.66";
sending it to mssql will be the same regardless.
Are you just wanting to make sure it is formatted properly, or is an actual float?

Categories