This question already has answers here:
Why is PHP printing my number in scientific notation, when I specified it as .000021?
(7 answers)
Closed 10 months ago.
I have the below problem, how to make it appear 0.00004 as string after multiplication?
$v = -0.00004;
$v = $v * -1;
echo $v; // 4.0E-5
Long story
As a result I need to save into MySQL database but no problem with that because I use below query:
$sql_insert = $conn->prepare("insert into tbl_transaction (amount) values ($v)");
However when I output to my HTML it showing 4.0E-5. I tried to use number_format but in some cases the decimals will go far more than this so it is not a choice.
Try this.
echo sprintf('%f', $v);
Or:
$b = sprintf('%f', $v);
echo $b;
You can try as below.
$v = -0.00004;
$v = $v * -1;
echo number_format($v, 5);
Hope this will help.
After formatting the number with the desired precision you need to strip the trailing zeros.
This should do the trick:
$v = -0.00004;
$v = number_format($v * -1, 20);
print rtrim($v, 0);
If you var_dump($v) after the first assignment, you'll see that the "problem" is NOT the calculation.
$v = -0.00004;
var_dump($v); //float(-4.0E-5)
number_format() can be used to return a formatted version of your value. You can get the length of the string value, and pass that to number_format.
var_dump(number_format($v,strlen(strval($v)))); // string(10) "-0.0000400"
So, your code would be:
$v = -0.00004;
$v = $v * -1;
$v = number_format($v,strlen(strval($v)));
echo $v //0.000040
You don't need to use number_format until you're ready to display the value because the exponential number is the same value as the formatted / decimal number.
Related
I have these numbers:
0.00000100
0.00100000
0.01000000
0.00001000
and I want to remove unnecessary zero in decimal by using this :
$decimal_cutter = (float) $decimal_cutter;
echo sprintf('%f', $decimal_cutter) . '<br>';
and it works for some numbers, some others produce this :
1.0E-6
0.001
0.01
1.0E-5
I want to use decimal, instead of scientific format.
Please note, I tried to use number_format() also, but keep in mind that by setting number of decimal points can cut the rest of numbers. I just want to remove the 0 after 1.
If you are simply worried about not displaying those characters, why not simply trim them?
You can simply call rtrim($yourNumber, '0')
E.g.:
$a = [];
$a[] = "0.00000100";
$a[] = "0.00100000";
$a[] = "0.01000000";
$a[] = "0.00001000";
foreach ($a as $b) {
echo rtrim($b, '0'), "\n";
}
Which outputs:
0.000001
0.001
0.01
0.00001
Logically this approach requires that you any of the decimal digits is different from 0, otherwise a number such as 2.0000 would be displayed as 2., which might not be ideal.
You could build a more general purpose solution using preg_replace
$a = [];
$a[] = "0.00000100";
$a[] = "0.00100000";
$a[] = "0.01000000";
$a[] = "0.00001000";
$a[] = "2.00000000";
$a[] = "2.01011000";
$a[] = "0.00123000";
foreach ($a as $b) {
echo preg_replace('|(?<!\.)0+$|', '', $b), "\n";
}
This looks for all trailing zeroes not preceded by a period, and would output:
0.000001
0.001
0.01
0.00001
2.0
2.01011
0.00123
Since you mention your data is always "1", here's a simple way:
$s = '0.00000100';
echo strstr($s, '1', true).'1';
Note: make sure you convert your data to string first
using php. I have the following number
4,564,454
454,454,454
54.54
65.43
I want to convert these into number for calculating. How can I do it? Right now, the type of these number is string.
Note: the comma is not a separate of a number, it is a notion to make a number nicer. I got this format from the ajax request, I cant change the format though. So, I have to use it.
Thanks
$var = floatval(str_replace(",", "", "454,454,454"));
$a='4,5,4';
$ab= explode(',', $a);
foreach ($ab as $b)
{
$sum+=$b; //perform your calculation
}
echo $sum;
First you need to remove ,(comma) from your string as below :
$str=str_replace(",", "", "454,454,454");
Then converting in numeric:
$int = (int)$str;
or
$int=intval($str);
now do your calculation using $int variable.
try this code
$str = '4,564,454';
$str2 = '454,454,454';
$str3= '54.54';
$str4= '65.43';
$sum=0;
$sum += array_sum(explode(',',$str));
$sum += array_sum(explode(',',$str2));
$sum += $str3;
$sum += $str4;
echo $sum;
I have a string like this:
9.018E-14
Now I want to convert to this to the normal decimal numbers.
MyGeekPal has a nice article on it.
Code:
<?php
$total_time = 2.8848648071289E-5;
echo exp2dec($total_time);
function exp2dec($number) {
preg_match('/(.*)E-(.*)/', str_replace(".", "", $number), $matches);
$num = "0.";
while ($matches[2] > 0) {
$num .= "0";
$matches[2]--;
}
return $num . $matches[1];
}
?>
If your input is a float
If you have $number = 0.00023459 then printing this value in PHP will probably result in this exponential format. It doesn't mean the variable is stored that way; it's just an output artefact.
Use printf to work around this and gain control over your numeric output.
If your input is a string
Why the complexity?
$matches = Array();
if (preg_match('/(.*)E-(.*)/', $number, $matches)) {
$number = $matches[1] * pow(10, -1*$matches[2]);
}
Though you can tighten up the regex a bit:
$matches = Array();
if (preg_match('/(\d+(?:\.\d+)?)E(-?\d+)/i', $number, $matches)) {
$number = (float)$matches[1] * pow(10, (int)$matches[2]);
}
Live demo
EDIT: Here is some PHP magic:
$stringval = "12e-3";
$numericval = 0 + $stringval;
From the PHP docs:
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.
If you need a more flexible format (e.g. extract four numbers from the same string), use sscanf like this:
$stringval = "12e-3";
$numericval = sscanf($stringval, "%f")[0];
echo $numericval;
I have an array that contains values of 1 or 0 representing true or false values. e.g.
array(1,0,0,1,0,1,1,1,1);
I want to compress/encode this array into the shortest string possible so that it can be stored within a space constrained place such as a cookie. It also need to be able to be decoded again later. How do I go about this?
ps. I am working in PHP
Here is my proposal:
$a = array(1,0,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1,1,0,0,1,0,1,1,1,1);
$compressed = base64_encode(implode('', array_map(function($i) {
return chr(bindec(implode('', $i)));
}, array_chunk($a, 8))));
var_dump($compressed); // string(8) "l8vlBw=="
So you get each 8 characters (which in fact is a binary 0..255), convert them to an integer, represent as an ASCII character, implode it to a string and convert to base64 to be able to save it as a string.
UPD:
the opposite is pretty straightforward:
$original = str_split(implode('', array_map(function($i) {
return decbin(ord($i));
}, str_split(base64_decode($compressed)))));
How exactly I wrote it (just in case anyone interesting how to write such unreadable and barely maintainable code):
I've written the $original = $compressed; and started reversing the right part of this expression step by step:
Decoded from base64 to a binary string
Split it to an array
Converted every character to its ASCII code
Converted decimal ASCII code to a binary
Joined all the binary numbers into a single one
Split the long binary string to an array
Dont use serialize. Just make a string of it:
<?php
$string = implode( '', $array );
?>
You are left with an string like this:
100101111
If you want to have an array again, just access it like an array:
$string = '100101111';
echo $string[1]; // returns "0"
?>
Of course you could also make it a decimal and just store the number. That's even shorter then the "raw" bits.
<?php
$dec = bindec( $string );
?>
How about pack and unpack
$arr = array(1,1,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1,1,1,1);
$str = implode($arr);
$res = pack("h*", $str);
var_dump($res);
$rev = unpack("h*", $res);
var_dump($rev);
output:
string(10) # Not visible here
array(1) {
[1]=>
string(20) "11110011010011001111"
}
Here is my solution based on zerkms answer, this deals with the loss of leading 0's when converting decimals back into binary.
function compressBitArray(array $bitArray){
$byteChunks = array_chunk($bitArray, 8);
$asciiString = implode('', array_map(function($i) {
return chr(bindec(implode('', $i)));
},$byteChunks));
$encoded = base64_encode($asciiString).'#'.count($bitArray);
return $encoded;
}
//decode
function decompressBitArray($compressedString){
//extract origional length of the string
$parts = explode('#',$compressedString);
$origLength = $parts[1];
$asciiChars = str_split(base64_decode($parts[0]));
$bitStrings = array_map(function($i) {
return decbin(ord($i));
}, $asciiChars);
//pad lost leading 0's
for($i = 0; $i < count($bitStrings); $i++){
if($i == count($bitStrings)-1){
$toPad = strlen($bitStrings[$i]) + ($origLength - strlen(implode('', $bitStrings)));
$bitStrings[$i] = str_pad($bitStrings[$i], $toPad, '0', STR_PAD_LEFT);
}else{
if(strlen($bitStrings[$i]) < 8){
$bitStrings[$i] = str_pad($bitStrings[$i], 8, '0', STR_PAD_LEFT);
}
}
}
$bitArray = str_split(implode('', $bitStrings));
return $bitArray;
}
I have a whole bunch of percentages stored as XX% (e.g. 12%, 50%, etc..) I need to remove the percentage sign and then multiply the percent against another variable thats just a number (e.g. 1000, 12000) and then output the result. Is there a simple way to strip the percentage sign and then calculate the output with PHP? Or should I consider some sort of JS solution?
You could use rtrim():
$value = ((int) rtrim('12%', '%')) * 1000';
Edit
You don't strictly need to call rtrim() , as it casts to an int ok with the percentage sign. It is probably cleaner to strip it though.
var_dump (12 === (int) '12%');
//output: bool(true)
You can make use of preg_replace_callback as:
$input = '12%, 50%';
$input = preg_replace_callback("|(\d+)%|","replace_precent",$input);
echo $input; // 12000, 50000
function replace_precent($matches) {
return $matches[1] * 1000;
}
Try this:
$number = str_replace('%', '', '100%');
$result = intval($number) * 5000; // or whatever number
echo $result;
If you use trim() or str_replace() in PHP you can remove the percent sign. Then, you should be able to multiply the resulting number (php is weakly typed after all).
<?php
$number = str_replace("%", "", $percentString);
$newNumber = ((int) $number) * 1000;
echo $newNumber;
?>
You can use str_replace. You can also pass an array of subjects into str_replace to have them all replaced.
<?php
$number = str_replace("%", "", $percentage);
$result = $number * $other_var;
print $result;
?>
<?php
$input=array('15%','50%','10.99%','21.5%');
$multiplier=1000;
foreach($input as $n){
$z=floatval($n)*$multiplier;
print("$z<br>");
}
?>