i have value in php variable like that
$var=\'2.500000550\';
echo $var
what i want is to delete all decimal points after 2 digits.
You're requesting a function that returns "2.50"
and not 2.5
, so you aren't talking about arithmetic here but string manipulation. Then preg_replace
is your friend:
$truncatedVar = preg_replace('/\.(\d{2}).*/', '.$1', $var);
// "2.500000050" -> "2.50", "2.509" -> "2.50", "-2.509" -> "2.50", "2.5" -> "2.5"
If you want to do it with arithmetic, simply use:
$truncatedVar = round($var * 100) / 100);
// "2.500000050" -> "2.5", "2.599" -> "2.59", "-2.599" -> "2.59"
floor(2.500000550 * 100) / 100;
This should do your task...
use sprintf
sprintf("%01.2f", $var);
If you don't want to round the number but you want to remove the decimal places you can use "substr" method
substr(string, start, length);
substr(4.96, 0, -1);
The following is (what I believe is - please correct me if not) a robust mathematical* solution, based mostly on the information from several other answerers here, and a small amount from me
(*Which is not to suggest there's anything wrong with Liphtier's regex-based answer - just that I can see purists wanting to avoid regex for what is arguably a mathematical problem.)
sprintf()
, number_format()
(and round()
, obviously), are all performing a rounding operation so are not appropriate for the non-rounding truncation requested in the question (not on their own, at least).pow()
to get the right factor based on a specified precision).floor()
(or presumably ceil()
) may produce unintended results for negatives without use of abs()
.abs()
to get a negation factor, we need to account for the special case when the input is 0.The code I'm using is:
public static function truncate_decimal($number, $leavePlaces = 2)
{
if ($number == 0) return 0;
$negate = $number / abs($number);
$shiftFactor = pow(10, $leavePlaces);
$epsilon = pow(10, -1 * $leavePlaces);
return floor(abs($number) * $shiftFactor + $epsilon) / $shiftFactor * $negate;
}
someone posted here about
floor(2.500000550 * 100) / 100;
function cutAfterDot($number, $afterDot = 2){
$a = $number * pow(10, $afterDot);
$b = floor($a);
$c = pow(10, $afterDot);
echo "a $a, b $b, c $c<br/>";
return $b/$c ;
}
echo cutAfterDot(2.05,2);
a 205, b 204, c 100
2.04
so in raw form don't use it... But if you add a little epsilon...
function cutAfterDot($number, $afterDot = 2){
return floor($number * pow(10, $afterDot) + 0.00001) / pow(10, $afterDot);
}
it works!