Reputation: 1125
I am trying to find a way to remove a decimal point from a number.
E.g.
1.11 would equal 111
9.99 would equal 999
1.1111 would equal 11111
Can't seem to find the function I need to do this. I have been googling to find this function but no luck.
I have tried these functions but it is not what I am looking for:
floor(99.99) = 99
round(99.99) = 100
number_format(99.99) = 100
Upvotes: 2
Views: 527
Reputation: 13544
We can use explode:
$num = 99.999;
$final = '';
$segments = explode($num, '.');
foreach ($segments as $segment){
$final .= $segment;
}
echo $final;
Checkout this demo: http://codepad.org/DMiFNYfB
Generalizing the solution for any local settings variations we can use preg_split as follows:
$num = 99.999;
$final = '';
$pat = "/[^a-zA-Z0-9]/";
$segments = preg_split($pat, $num);
foreach ($segments as $segment){
$final .= $segment;
}
echo $final;
Also, there are another solution using for loop:
<?php
$num = 99.999;
$num = "$num"; //casting number to be string
$final = '';
for ($i =0; $i < strlen($num); $i++){
if ($num[$i] == '.') continue;
$final .= $num[$i];
}
echo $final;
Upvotes: 3
Reputation: 431
Try:
$num = 1.11; // number 1.11
$num_to_str = strval($num); // convert number to string "1.11"
$no_decimals = str_replace(".", "", $num_to_str); // remove decimal point "111"
$str_to_num = intval($no_decimals); // convert back to number 111
All in one line would be something like:
$num_without_decimals = intval(str_replace(".", "", strval(1.11)));
Upvotes: 1
Reputation: 311843
You could just treat it as a string and remove the .
character:
$num = str_replace ('.', '', $num);
Upvotes: 2
Reputation: 1446
If you want to simply remove the decimal, you can just replace it.
str_replace('.', '', $string);
Upvotes: 2
Reputation: 59701
This should work for you:
<?php
$str = "9.99";
echo $str = str_replace(".", "", $str);
?>
Output:
999
Upvotes: 3