I have the following data.
$96.2k
$75.2k
$44.4k
$35.6k
Etc.......
What I am wanting to do is replace the decimal and any number(s) following the decimal. Then i want to round the whole number to the nearest tenth.
All of my data is between 10k
and 90k
So the expected output would be..
$100k
$80k
$40k
$40k
I know i can use preg_replace('/\.[0-9]+/', '', $data);
to remove the decimal and numbers but can i not use regular preg_replace with a function?
<?php
$number = '$96.2k';
$number = str_replace(array('$', 'k'), '', $number);
$number = round($number, -1); // -1 rounds to nearest 10
echo '$' . $number . 'k';
// $100k
?>
More info on round here: http://php.net/manual/en/function.round.php
Instead of using preg_replace
, I would use preg_replace_callback
:
$data = preg_replace_callback('/([0-9]+)\.[0-9]+/', # capture first group of digits
function($m) { # $m is your captured match
return round($m[1], -1); # round our captured match
}, $data);
The will round your match ($m
) to the nearest 10. Have a look at round
for the use of parameters.
See working demo