PHP 7.3.4
When I use
$val = '1,234.00';
echo number_format($val, 2, '.', '');
I get
1 (desired output is 1234.00)
If I do
$val = '1,234.00';
$val = str_replace([',', '$'], '', $val);
echo number_format($val, 2, '.', '');
I get
1234.00
Why doesn't the first one work? What am I missing about the number_format function?
There are 2 important points which need to understand about number_format()
number_format() takes a float as the 1st argument. If string given than convert it in Integer/Float. If found any character in string take the integer part before that character.
return a number with grouped thousands that means a string.
First check the datatype
$a = 1234; // integer
$a = 1234.00; // float
$a = "1234.00"; // string and we can use it as int/float
$a = "1,234.00"; // string but we can't use as int/float because of comma
In first example
$val = '1,234.00';
echo number_format($val, 2, '.', '');
The type of $val is string. So number_format() takes only the int/float part of string and when found any character trim that number. So taking only 1 and you are getting 1.00.
Let's try with
$val = '12,34.00';
echo number_format($val, 2, '.', '');
$val = '12Z34.00'; // also check with this
echo number_format($val, 2, '.', '');
And you will get the result 12.00 for both.You can also check with
$val = 12,34;
echo number_format($val, 2, '.', '');
And you will get
PHP Parse error: syntax error, unexpected ','
That means it not assuming $val as a string. Lets we check with a string without ',' and we will again use number_format() with converted number.
$val = "1234.00";
echo $first = number_format($val, 2, '.', ',');
echo $second = number_format($first, 2, '.', ',');
the output of above example is:
1,234.00
1.00
So $val work like a float number and in $first we are getting a string number and for $second it is separate again with comma and the output is 1.00. So if you have a string with comma, first you need to remove comma from that string then format that using number_format()
Related
How can I remove the comma separator from a number
e.g. 40,000 resulting in 40000 in php?
function cleanData($a) {
$a = (int)str_replace( '.', '', $a );
return $a;
}
I've tried using this function only when I compare the result (===) of cleanData($a) with 40000 it doesn't match types?
Try this:
function cleanData($a) {
$a = (int) str_replace( ',', '', $a );
return $a;
}
First of all, you want to replace commas (,), not periods. Second, === checks types as well as value so you must typecast from a string to an integer using (int). You did that part, but you weren't replacing commas so the value was 40, not 40000.
Example:
<?php
var_dump((int) str_replace( '.', '', '40,000')); // int(40)
var_dump((int) str_replace( ',', '', '40,000')); // int(40000)
I have a question variable e.g. "4X9"
how can i split this into 3 different variables, to have an integer 4, integer 9 and string X ?
I tried using
$arr = explode('X', $question);
$before = $arr[0];
$bbefore = str_replace('"', "", $before);
$newBefore =(int)$before;`
and the same for after.
list($before, $x, $after) = str_split(str_replace('"', '', $question));
1) Explode string by character using str_split()
2) Use list() to make assigning them variables clearer
3) If $before and/or $after are integers you can cast them after this line of code
list($before, $x, $after) = str_split(str_replace('"', '', $question));
$before = (int) $before;
$after = (int) $after;
Demo
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 a string and this string should be an array.
But the first 2 letters are variable and I need the 5 next digits (whether empty or not). The last 5 digits are numeric with a decimal point or empty ( $string="AB3 . ";)
An example:
$string = "AB10.00";
$arr[0] = "AB";
$arr[1] = "10.00";
I would like to use preg_split() for this.
You mean substr() ?
$string = "AB10.00";
$arr[0] = substr($string, 0, 2); // $arr[0] == 'AB'
$arr[1] = substr($string, 2); // $arr[1] == '10.00'
I suspect that this has been asked before, but I have no idea what it's actually called, so I couldn't find anything.
I am creating a browser based game in which the player has a 10x10 grid. Each grid square has a few aspects to it, some as binary flags and other as hex values.
To store this information in an array, I want a given cell to contain the following:
"9A0101" where 9A is the tile type, and the 0s and 1s are binary flags about that map tile.
I want to be able to take "9A0101" and split it into "9A", "0", "1", "0", and "1" as separate variables.
TLDR:
How do I slice up a string in PHP? The string will always be the same length, and the parts where I want to cut it will always be at the same offsets.
use substr() to get the parts of string
<?php
echo substr('9A0101', 0,2); // 9A
echo substr('9A0101', 2, 1); // 0
echo substr('9A0101', 3, 1); // 1
echo substr('9A0101', 4, 1); // 0
echo substr('9A0101', 5, 1); // 1
?>
what about substr() ? :
<?php
$str = '9A0101';
echo substr($str,0,2);
echo substr($str,2,1);
echo substr($str,3,1);
echo substr($str,4,1);
echo substr($str,5,1);
?>
You can the substr() function
<?php
$str = "9A0101";
$arr = Array();
$arr[0] = substr($str, -6, 2);
$arr[1] = substr($str, -4, 1);
$arr[2] = substr($str, -3, 1);
$arr[3] = substr($str, -2, 1);
$arr[4] = substr($str, -1, 1);
foreach($arr as $key => $val) {
echo($key . "=>" . $val . '<br/>');
}
?>
Or maybe can use the str_split() function.
$str = "9A0101";
//splitting the string
$array = str_split($str, 2);
var_dump($array);
If you are looking for a single function call, regex can serve you well.
preg_split('~(^..|.)\K~', $string);
The above will split the string on the zero-width position after the first two characters of the string or each subsequent character. \K means forget what is already matched.
If you want to save the 5 values as individual variables, then you can use list() or array destructuring syntax. Demo
[$type, $one, $two, $three, $four] = preg_split('~(^..|.)\K~', $string);
If you wish, you can even access the single byte characters by their string offset. Demo
$type = $string[0] . $string[1];
$one = $string[2];
$two = $string[3];
$three = $string[4];
$four = $string[5];