Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using explode
)
You should always be careful about different locales. European locales use a comma for the thousands separator, so the accepted answer would not work. See below for a revised solution:
function countDecimalsUsingStrchr($stringValue){
$locale_info = localeconv();
return strlen(substr(strrchr($stringValue, $locale_info['decimal_point']), 1));
}
see localeconv
If you want readability for the benefit of other devs, locale safe, use:
function countDecimalPlacesUsingStrrpos($stringValue){
$locale_info = localeconv();
$pos = strrpos($stringValue, $locale_info['decimal_point']);
if ($pos !== false) {
return strlen($stringValue) - ($pos + 1);
}
return 0;
}
see localeconv
Less code:
$str = "1.1234567";
echo strpos(strrev($str), ".");
$value = 182.949;
$count = strlen(abs($value - floor($value))) -2; //0.949 minus 2 places (0.)
First I have found the location of the decimal using strpos
function and increment the strpos
postion value by 1 to skip the decimal place.
Second I have subtracted the whole string length from the value I have got from the point1.
Third I have used substr
function to get all digits after the decimal.
Fourth I have used the strlen
function to get length of the string after the decimal place.
This is the code that performs the steps described above:
<?php
$str="98.6754332";
echo $str;
echo "<br/>";
echo substr( $str, -(strlen($str)-(strpos($str, '.')+1)) );
echo "<br/>";
echo strlen( substr( $str, -(strlen($str)-(strpos($str, '.')+1))) );
?>
This will work for any numbers, even in scientific notation, with precision up to 100 decimal places.
$float = 0.0000005;
$working = number_format($float,100);
$working = rtrim($working,"0");
$working = explode(".",$working);
$working = $working[1];
$decmial_places = strlen($working);
Result:
7
Lengthy but works without complex conditionals.