How to make 2.4212744961175E+18 like 2421274496117503233 in PHP - php

I am using GoToWebinar API and getting following value A which is correct but i have another function which takes it as parameter and gives customer list.
A = 2.4212744961175E+18
B = 2421274496117503233
Problem is function is not getting value A, if i am using value B its working
Can any one tell me how can i convert A to like B so it will work.
Thanks

<?php $var = sprintf("%f",'2.4212744961175E+18'); ?>
replace %f to your integer if you are not using float

Just run the number through number_format. For example:
$a = number_format(2.4212744961175E+18, 0);
Or start using third party PHP libraries that deal with numbers. BC Math, GMP, Math etc.

Finally got the solution and that large value with + sign was coming due to large integar and PHP 5.3 or less versions have that bug which has been resolved in PHP5.4, i tested on 5.4 version and it gave correct output.
See this link for details

Yea I was having the same issue, looks like you had to add that last argument at the end to make that value a string instead of a float:
$data = json_decode( $jsonString, true, 512, JSON_BIGINT_AS_STRING );

Related

PHP format number before insert into database

i'm using $_POSTto send form values to PHP and then insert into database, i have some inputs for prices values that looks like this:
1.000.000,00 (1 million in BRL "Brazilian Real")
I need to convert it to 1000000.00 (DECIMAL(10,2) to insert into database)
How can i do that using PHP number_format()?
Thanks!
EDIT
If number_format() is not the function i'm looking for, what's best to be using in this case?
Also, i need help finding a solution, even if the user value is 100.000,00
You can not do that with number format, it works other way around.
The thing that you do is bad practice, View layer should send primitive data to Controller - if you are using some advanced javascript component to represent to the user formatted number, that is fine, but underlaying form control should send primitive data, i.e. 10000000.00
Now, if nothing that I have stated to you is not applicable at this particular moment, and having in mind that this format that you have send is fixed (dot for thousand separator, coma for decimal separator), you can clean the value by using simple str_replace.
But, the trick is to replace first dot with empty string, then coma with dot.
str_replace(',', '.',str_replace('.', '', $number));
Got it?
But know that what you are doing is bad approach and wrong implementation, eventually, it will bite you in the a**.
<?php
$number = '1.000.000,00';
$replaced_number = str_replace(array('.',','), array('',''), $number);
echo number_format($replaced_number,2,'.','');
?>
The easiest way is to use str_replace() function:
<?php
$p = '1.000.000,00';
$p = str_replace('.', '', $p);
$p = str_replace(',', '.', $p);
echo $p;
At first replace the (.) and (,) with str_replace by '' and then use t the following function
number_format($replaced_number,$decimal)
If you have a look at php.net you will easily see the right syntax for your goal:
number_format($number,2,'.','')
The first parameter is the number of decimal places that in your case is 2.
The second is the symbol to use for decimal separator and the third is the one to be used for thousands that in your case will be nothing .

PHP Array: Is there a way to force all array keys to be string?

Edit: I have made a demo to my problem: http://codepad.org/ByNdAdCI
We use the following logic to set our arrays in 32 bit php:
private function formatAvailableOptions($availableOptions) {
$optionsAsArray = array();
foreach($availableOptions as $option){
$optionsAsArray[$option["entity_id"]] = $option["name"];
}
return $optionsAsArray;
}
Problem:
The $option["entity_id"] has grown too big to fit in 32 bit int, and as a result overflow when $optionsAsArray gets created. For example
$optionsAsArray[2147483648] = "hi";
becomes
$optionsAsArray[-2147483648] = "hi";
I need the index to be 2147483648 as it's tied to ids in the database
This code is already shipped to the client, and the logic is used in many places that makes it infeasible to modify every single instance to
$optionsAsArray[strVal(2147483648)] = "hi";
to make it run properly by using string type as key to associative array.
What is the best solution in this case? Is there a global config option for me to force all php arrays to use string as keys to get around this problem?
Seems, that it doesn't like floats as keys ;) So the type cast to float fails. You already mentioned your solution in the question (strVal($var), or (string) $var, or just "$var"). If your customers run PHP in 64bit (what they should ;)) they don't see any difference. Because this is obviously a bug you should consider to fix it and publish an update to your customers. There is no option, or setting, that converts a 32bit installation into a 64bit one on the fly.

highcharts with number_format

i'm working with Highcharts, and i'm having some problem with number_format.
formating the number $variable = 1008000 :
number_format($variable, 2,',','.')
the result is: 1.008.000,00 (this is what i need)
but, highcharts transform 1.008.000,00 to 1.008
how can i deal with this problem?
Note that in English the number should be 1,008,000.00
You could either change it in your number_format() call or try changing the decimal point value in Hightcharts (http://www.highcharts.com/ref/#lang)
note one thing, we do not need to set the number format for high chart...
you can pass directly 1008000 it will be auto adjust with this value...
Check this...Good luck
Thanks
Apart from lang parameters http://api.highcharts.com/highstock#lang.thousandsSep you can also use Highcharts.numberFormat() for labels / tooltip which can be used in formatter .
http://api.highcharts.com/highstock#highcharts.numberFormat()
http://api.highcharts.com/highstock#tooltip.formatter

Convert a Perl code to PHP

I need to convert the following perl function to php:
pack("SSA12AC4L",
$id,
$loc,
$name,
'ar',
split(/\./, $get->getIP),
time+(60*60);
I use the following code (to test) in PHP:
echo pack("SSA12AC4L",
'25',
'00001',
'2u7wx6fd94fd',
'f',
preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY),
time()+(60*60));
But I'm getting the following error:
Warning: pack() [function.pack]: Type C: too few arguments in D:\wamp\www\test.php on line 8
Any suggestions? Thanks a lot.
From the PHP documentation for pack().
Pack given arguments into binary
string according to format.
The idea for this function was taken
from Perl and all formatting codes
work the same as in Perl. However,
there are some formatting codes that
are missing such as Perl's "u" format
code.
Surely it should just work as is? You may need to rename some variables
Sometimes the error statements mean something worth reviewing. Too few arguments may mean there is a need to review each input used in the PHP pack statement aligns with the expected format.
For instance, did you take into account the 'ar' field used in the perl pack statement? You might be off in the resulting packed data by one field because of that.
It looks like you're having trouble with the fact that in Perl, if a function call is placed in the middle of a parameter list, and the called function returns a list, the items in that list are "flattened" to produce multiple arguments to the outer function; PHP doesn't do anything similar, and that's where you're getting your argument mismatch (the split should be producing four arguments to pack, but PHP only sees one -- an array value).
Fortunately the way around this is pretty easy, because there are builtin functions that will replicate what you need without any gymnastics. Try:
echo pack("SSA12ANL",
'25',
'00001',
'2u7wx6fd94fd',
'f',
ip2long('10.2.1.1'),
'1278761963');
or if that somehow fails:
echo pack("SSA12Aa4L",
'25',
'00001',
'2u7wx6fd94fd',
'f',
inet_pton('10.2.1.1'),
'1278761963');
The problem is that the code is giving to pack() (I am referring the the last arguments) a character, an array, and an integer. As the code C wants 4 characters, that is the cause of the error.
The code should be something like
$split = preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY);
echo pack("SSA12AC4L",
'25',
'00001',
'2u7wx6fd94fd',
'f',
$split[0],
$split[1],
$split[2],
$split[3],
time()+60*60
);
Then, there is no reason to use preg_split() in this case, when explode() can be used instead. Regular expressions should be used only when strictly necessary because the regular expression functions are slower, compared to other string functions.
I think that the problem is that preg_split returns an array. So the array is inserted as the first char, the time as the second, and two chars are left.
I don't know how to fix this problem, but to create a temporary array:
$ip = explode('.','10.2.1.1');
And then:
echo pack("SSA12AC4L",
'25',
'00001',
'2u7wx6fd94fd',
'f',
$ip[0],
$ip[1],
$ip[2]
$ip[3],
time()+(60*60));
The problem is that php preg_split is converting it to an array. You need an unsigned char, so use
$x = intval(implode("", preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY)));
echo pack('SSA12ACL',
'25',
'00001',
'2u7wx6fd94fd',
'f',
$x,
time()+(60*60));
Let know how it goes.
My first suggestion is that you carefully read the documentation. This problem has little to do with perl and much to do with understanding what the function expects. My second suggestion is to get in the habit of feeling a little nervous whenever you copy some code. Nervous enough to pay extra attention to the code, the documentation, etc. At the very least, when a client/boss/whoever asks you what that bit of copied code does, you should have a good answer.
The first parameter to pack() is a format string. This determines how it formats the parameters when it creates the output.
From the documentation for pack():
The format string consists of format
codes followed by an optional repeater
argument. The repeater argument can be
either an integer value or * for
repeating to the end of the input
data. For a, A, h, H the repeat count
specifies how many characters of one
data argument are taken, for # it is
the absolute position where to put the
next data, for everything else the
repeat count specifies how many data
arguments are consumed and packed into
the resulting binary string.
So, the problem is that your format string isn't appropriate for the arguments you pass to pack(). Now, keep in mind that I have to guess at the appropriate format string for your needs. You have to read the documentation and determine the correct format string.
The following works just fine:
echo pack("SSA12ACL",
'25',
'00001',
'2u7wx6fd94fd',
'f',
preg_split('/\./','10.2.1.1', -1, PREG_SPLIT_NO_EMPTY),
'1278761963');
The function preg_split() returns a single array. However, the 'C4' in the original format string expects to take in 4 parameters. Based on my count, the original format string implied 9 parameters, not 6.
I haven't looked at this very long, but the first thing I noticed was that you have one open paren and three closing. Is "time" supposed to be $time?

How can I convert all values of an array to floats in PHP?

I am fetching an array of floats from my database but the array I get has converted the values to strings.
How can I convert them into floats again without looping through the array?
Alternatively, how can I fetch the values from the database without converting them to strings?
EDIT:
I am using the Zend Framework and I am using PDO_mysql. The values are stored one per column and that is a requirement so I can't serialize them.
array_map('floatval', $array) only works on single dimensional arrays.
I can't floatval the single elements when I use them because I have to pass an array to my flash chart.
The momentary, non-generic solution is to extract the rows and do array_map('floatval',$array) with each row.
You could use
$floats = array_map('floatval', $nonFloats);
There is the option PDO::ATTR_STRINGIFY_FETCHES but from what I remember, MySQL always has it as true
Edit: see Bug 44341 which confirms MySQL doesn't support turning off stringify.
Edit: you can also map a custom function like this:
function toFloats($array)
{
return array_map('floatval', $array);
}
$data = array_map('toFloats', $my2DArray);
How are you getting your data? mysql, mysqli or PDO, some other way or even some other database?
you could use array_map with floatval like so:
$data = array_map('floatval', $data);
but that still executes a loop and i think it assumes you only have one column in your data.
you're probably best of casting to float when you use your value, if you have to. php is likely to do a good job of interpreting it right anyway.
LOL... are you working on the same project I am tharkun?
I just finished (last night) creating something, in a ZF based project, that uses pdo_mysql to retrieve and format data and then output it as xml for use in a flash piece. The values were going in as strings but needed to be floats.
Since I'm also the one who wrote the part that gets the data and the one who created the database I just made sure the data was converted to float before it went into the database.
I simply cast the values as float as part of some other formatting, for what it is worth.
protected function _c2f($input)
{
$input = (float)$input;
$output = round(($input * 1.8) + 32, 2);
return $output;
}
I found an easy way for this operation.
You can do this just by adding foreach loop to your code. foreach loop is used to fetch your array string data one by one. and then, you can simply convert this by function number_format. i used 2 place after convert to float value. i.e it used to print value after dot value 2 place.
$example= array("12.20", "15.05", "55.70");
foreach($example as $float)
{
$update_value = number_format($float,2);
echo $update_value."<br>";
}
Not sure what you're asking here? You can cast a string to a float, using (float) $string, but since PHP is dynamically typed, that will happen anyway, when needed. There is no reason to do an explicit cast.
What are you using floating point values for?

Categories