What's a correct way to round (or cut) a PHP float after 3 characters, not counting 0's?
Example:
0.12345 => 0.123
0.012345 => 0.0123
0.0001239 => 0.000124
What's a correct way to round (or cut) a PHP float after 3 characters, not counting 0's?
Example:
0.12345 => 0.123
0.012345 => 0.0123
0.0001239 => 0.000124
You can use regex to capture the zeros and dots separated from digits and handle them separately.
$arr = [0.12345,0.012345,0.0001239];
Foreach($arr as $val){
Preg_match("/([0\.]+)([0-9]+)/", $val, $match);
Echo $match[1]. Substr(round("0.".$match[2],3),2,3)."
";
}
The regex works by first capture group is grabbing 0 and dots greedy, so any dots or zeros in sequence is captured.
Then the second group captures 0-9, but since the first group is greedy this can't start with 0.
So second group has to start with 1-9 then any 0-9 digits.