PHP Convert String into Float/Double - php

I have list of string (size in bytes), I read those from file. Let say one of the string is 2968789218, but when I convert it to float it become 2.00.
This is my code so far :
$string = "2968789218";
$float = (float)$string;
//$float = floatval($string);
//the result is same
// result 2.00
Anyone?
Solved
The problem was actually the encoding. It's fine now when I change the file encoding :D

Surprisingly there is no accepted answer. The issue only exists in 32-bit PHP.
From the documentation,
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
In other words, the $string is first interpreted as INT, which cause overflow (The $string value 2968789218 exceeds the maximum value (PHP_INT_MAX) of 32-bit PHP, which is 2147483647.), then evaluated to float by (float) or floatval().
Thus, the solution is:
$string = "2968789218";
echo 'Original: ' . floatval($string) . PHP_EOL;
$string.= ".0";
$float = floatval($string);
echo 'Corrected: ' . $float . PHP_EOL;
which outputs:
Original: 2.00
Corrected: 2968789218
To check whether your PHP is 32-bit or 64-bit, you can:
echo PHP_INT_MAX;
If your PHP is 64-bit, it will print out 9223372036854775807, otherwise it will print out 2147483647.

$float = floatval($string);
Ref : http://www.php.net/floatval

Try using
$string = "2968789218";
$float = (double)$string;

If the function floatval does not work you can try to make this :
$string = "2968789218";
$float = $string * 1.0;
echo $float;
But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ )
Maybe the problem is on your server ?

Related

Printing big numbers in PHP

The number is 13911392101301011 and regardless of using sprintf or number_format i get the same strange result.
sprintf('%017.0f', "13911392101301011"); // Result is 13911392101301012
number_format(13911392101301011, 0, '', ''); // Result is 13911392101301012
sprintf('%017.0f', "13911392101301013"); // Result is 13911392101301012
number_format(13911392101301013, 0, '', ''); // Result is 13911392101301012
As you actually have the number as a string, use the %s modifier:
sprintf('%s', "13911392101301011"); // 13911392101301011
Note that PHP is using a signed integer internally. The size depends on your system.
32bit system:
2^(32-1) = 2147483648
64bit system:
2^(64-1) = 9223372036854775808
-1 because 1 bit is reserved for the signage flag.
Since you are dealing with large numbers here, you may want to keep them as strings and perform numerical operation on the string values using BCMath functions.
$val = "13911392101301011";
echo $val; // 13911392101301011
echo bcadd($val, '4'); // 13911392101301015
echo bcmul($val, '2'); // 27822784202602022
You can do easily this way :-
ini_set("precision",25); // change 25 to whatever number you want or need
$num = 13911392101301011;
print $num;
Documentation states that $number in number_format is float so there is explicit typecast. Equivalent would look like this:
sprintf('%017.0f', (float) "13911392101301011");
Float is precise to around 14 digits and your number has 17 digits.
Your number_format call is setting the . and , to blank
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
try this:
number_format(13911392101301011, 0, '.', ',');

from 1.297503E+17 to 129750300000000000

How can I get php to not use 1.297503E+17 on large int but 129750300000000000
code:
$dag = 29;
$maand = 03;
$jaar = 2012;
$expdate = $dag . "-" . $maand . "-" . $jaar;
$unixstamp = strtotime($expdate);
echo $unixstamp."<br />";
$winstamp = ($unixstamp + 11644560000) * 10000000;
I'm trying to use the number for a Timestamp in ldap.
That's what I would do (tested on 32b platform)
>> number_format(1.297503E+17,0,'.','')
'129750300000000000'
just be aware, that what you get back is a string, an will be converted back to float if you try doing any arithemtics on it. If you need to do math on large integers look into bc_math extension
PHP internally uses big enough integers. Your problem here is the use of echo:
printf ("%d", $winstamp);
$winstamp++;
printf ("%d", $winstamp);
output:
129775320000000000
129775320000000001
Hope this helps
echo rtrim(sprintf("%0.15f", $winstamp), "0.");
This uses sprintf to print a maximum of 15 decimal places, and then trims off any trailing 0 or . chars. (Of course, there's no guarantee that everything will be rounded nicely with trailing zeros as you might expect.)
If you just want a fixed size, then you can adjust the 15 and remove the rtrim.
Apparently, when PHP encounters a number that exceeds the upper limit of 2,147,483,647 for an integer, it automatically converts the number’s type from integer into a double.
Fortunately, we can format these numbers in scientific notation back to their standard integer form using the number_format() function. Here is how to do it:
$winstamp = 1202400000;
$formatted_stamp = number_format($winstamp , 0, '.', '');
echo $formatted_stamp; //outputs 1202400000 as expected

PHP - Comparing double to a string is weird?

I'm seeing some weird behavior in php when comparing a double to a string and was hoping someone could explain to me what is going on.
If I declare $num = 0.333;
and then test
$num == '0.333',
this comes out as true. If I then add 1 to $num and then subtract 1, then $num == '0.333' comes out as false. If I then cast $num as a string, the comparison goes back to being true. Why is it doing this?
Here's a sample:
<?php
$num = 0.333;
//returns 0.333 double Yes
echo $num, ' ', gettype($num), ' ', $num == '0.333' ? 'Yes' : 'No', '<br />';
$num += 1;
$num = $num - 1;
//returns 0.333 double No
echo $num, ' ', gettype($num), ' ', $num == '0.333' ? 'Yes' : 'No', '<br />';
$str = (string)$num;
//returns 0.333 string Yes
echo $str, ' ', gettype($str), ' ', $str == '0.333' ? 'Yes' : 'No', '<br />';
?>
Thanks.
You are comparing a floating point.
http://php.net/manual/en/language.types.float.php says:
never compare floating point numbers for equality.
The == compares for value, but 'across' types: one of the types must be converted before it can actually be compared. And this will result in comparison of floating point variables. That's why after doing a seemingly balanced action (+1 and -1) you're getting different results.
For comparing value AND type in PHP, you need to use 3 "=". like :
$num = 333
$num === 333 => true
$num === '333' => false
See here for more details http://php.net/manual/en/language.operators.comparison.php
A possible way to compare Float, is to use the method indicated in the comments of php.net regarding floats :
<?php
$number1=number_format($float1,2,'.','');
$number2=number_format($float2,2,'.''');
if($number1!=$number2){
echo 'do correction here!';
}
?>
But apparently, there isn't a definitive, best way to do it (or I didn't found it). Some convert the float to String, other does the code I just wrote.
As you like ;)
Take away point: use === instead of == to avoid type coercion.
The reason is that in the first instance $num is a double, but it is also equal to the string '0.333'.
Using === shows that the double 0.333 isn't the same as the string '0.333'.
The second one has done some addition, now the double isn't exactly 0.333 anymore, so it isn't the same as a string to to floating point inaccuracies.
The third one has cast 0.333 to a string, which is of course the same as the string.
To compare two float or double use http://php.net/manual/en/function.bccomp.php
You are comparing a float for which trailing digits are a problem.
One think you can do is convert the float to a string and take the first x characters (ie if you have a string '.333' that you're comparing it to, convert the float to a string and take the first four characters), or you can floor the float to the proper decimals before comparing it.

Removing all decimals in PHP

get this from my database:
252.587254564
Well i wanna remove the .587254564 and keep the 252, how can i do that?
What function should i use and can you show me an example?
Greetings
You can do it in PHP:
round($val, 0);
or in your MYSQL statement:
select round(foo_value, 0) value from foo
You can do a simply cast to int.
$var = 252.587254564;
$var = (int)$var; // 252
As Tricker mentioned you can round the value down or you can just cast it to int like so:
$variable = 252.587254564; // this is of type double
$variable = (int)$variable; // this will cast the type from double to int causing it to strip the floating point.
In PHP you would use:
$value = floor($value);
floor: Returns the next lowest integer value by rounding the value down if necessary.
If you wanted to round up it would be:
$value = ceil($value);
ceil: Returns the next highest integer value by rounding the value up if necessary.
You can just cast it to an int:
$new = (int)$old;
Convert the float number to string, and use intval to convert it to integer will give you 1990
intval(("19.90"*100).'')
Before using above answer what is your exact requirement please see bellow example output.
$val = 252.587254564;
echo (int)$val; //252
echo round($val, 0); //253
echo ceil($val); //253
$val = 1234567890123456789.512345;
echo (int)$val; //1234567890123456768
echo round($val, 0);//1.2345678901235E+18
echo ceil($val); //1.2345678901235E+18
$val = 123456789012345678912.512345;
echo (int)$val; //-5670419503621177344
echo round($val, 0);//1.2345678901235E+20
echo ceil($val); //1.2345678901235E+20
you can use echo (int) 252.587254564;
positive number:
round(252.587254564) // 253
floor(252.587254564) // 252
ceil(252.587254564) //252
(int)252.587254564 // 252
intval(252.587254564) // 252
~~252.587254564 // 252
negative number:
round(-252.587254564) // -253
floor(-252.587254564) // -253
ceil(-252.587254564) // -252
(int)-252.587254564 // -252
intval(-252.587254564) // -252
~~-252.587254564 // -252
if you want just remove decimals without round you can use one of above codes except round and floor(for negative number).
But I recommended the last one, it's simpler and faster using prefix ~~
And there is also a not quite advisable method:
strtok($value, ".");
This cuts of the first part until it encounters a dot. The result will be a string, not a PHP integer. While it doesn't affect using the result much, it's not the best option.
I see many answers, but the question is:
"Well i wanna remove the .587254564 and keep the 252, how can i do
that?"
Since the questioner is asking for php, the function in php will be the one for the job.
$newValue = floor($value);
In MySQL you can use:
select floor(field)
or in PHP you can use:
floor($value);

Rounding a number in PHP without converting it to the locale's representation

So, apparently PHP's round() outputs the result as a string formatted according to the current locale settings. round( 10000.326, 1 ) might return "1.000,3", which is fine if you intend to display the result right away, but not that great if you plan to work further with it.
php.net discussion hints that there is no way to stop round() from localizing the output. Is there really no "pure" rounding function in the library that would return an int or a float/double so that the result could be used in arithmetical operations, or is creating your own the only option?
round() doesn't output the result as a string formatted according to the current locale settings: it returns a float... and has no localization.
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
What you do with the result afterwards is more likely to localize it.
Where did you get the impression that round() returned a localized string?
I'm not too much of an expert, but perhaps number_format() might give you what you need? Based on the comments it doesn't appear to use locale, and I know it rounds.
Assuming rounding integers:
floor($value + .5);
And add precision like this (this is one digit):
$digits = 1;
floor($value * pow(10, $digits) + .5) / pow(10, d$igits);
use sprintf like :
$val = sprintf('%.1f', 1000.326);
gives : 1000.3
It's the automatic conversion to a string for output that probably causes the confusion. There's a more direct question about that. An example was helpful for me:
<?php
setlocale(LC_NUMERIC, 'en_US');
echo 1.234; // 1.234
setlocale(LC_NUMERIC, 'et_EE.UTF-8');
echo 1.234; // 1,234
echo number_format( 1.234, 2, '.', '' ); // 1.23
?>
The round function returns a float but the format is localized.
echo round(3.14159, 2);
setlocale(LC_ALL, 'fr_FR');
echo round(3.14159, 2);
This is what the original poster meant.
I suggest:
setlocale(LC_NUMERIC, 'en_US');
That will set the localization for the decimal separator to English (United States) and will be a period.
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
Where are you see string output???
if you want to force it to int you can type cast like this:
$rnum = (int) round( 10000.326, 1 );
not sure if this is what your looking for though.
you can get more info here http://php.net/manual/en/language.types.type-juggling.php
this is what i did to confirm, i am not sure what your trying to achieve exactely
but this might help
$var = (int) "1.000,3";
$var1 = "1.000,3";
if(is_string($var)) print "true";
else print "false";
if(is_int($var)) print "true";
else print "false";
if(is_string($var1)) print "true";
else print "false";
the results are:
false
true
true
please correct me if i am wrong. thanks.

Categories