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
)
I needed a solution that works with various number formats and came up with the following algorithms:
// Count the number of decimal places
$current = $value - floor($value);
for ($decimals = 0; ceil($current); $decimals++) {
$current = ($value * pow(10, $decimals + 1)) - floor($value * pow(10, $decimals + 1));
}
// Count the total number of digits (includes decimal places)
$current = floor($value);
for ($digits = $decimals; $current; $digits++) {
$current = floor($current / 10);
}
Results:
input: 1
decimals: 0
digits: 1
input: 100
decimals: 0
digits: 3
input: 0.04
decimals: 2
digits: 2
input: 10.004
decimals: 3
digits: 5
input: 10.0000001
decimals: 7
digits: 9
input: 1.2000000992884E-10
decimals: 24
digits: 24
input: 1.2000000992884e6
decimals: 7
digits: 14
Here's a function that takes into account trailing zeroes:
function get_precision($value) {
if (!is_numeric($value)) { return false; }
$decimal = $value - floor($value); //get the decimal portion of the number
if ($decimal == 0) { return 0; } //if it's a whole number
$precision = strlen($decimal) - 2; //-2 to account for "0."
return $precision;
}
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
Something like:
<?php
$floatNum = "120.340304";
$length = strlen($floatNum);
$pos = strpos($floatNum, "."); // zero-based counting.
$num_of_dec_places = ($length - $pos) - 1; // -1 to compensate for the zero-based count in strpos()
?>
This is procedural, kludgy and I wouldn't advise using it in production code. But it should get you started.
$decnumber = strlen(strstr($yourstr,'.'))-1
I used the following to determine whether a returned value has any decimals (actual decimal values, not just formatted to display decimals like 100.00):
if($mynum - floor($mynum)>0) {has decimals;} else {no decimals;}