Hi!
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)
Thanks,
Erwin
Hi!
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)
Thanks,
Erwin
You could try casting it to an int, subtracting that from your number and then counting what's left.
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.
function numberOfDecimals($value)
{
if ((int)$value == $value)
{
return 0;
}
else if (! is_numeric($value))
{
// throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
return false;
}
return strlen($value) - strrpos($value, '.') - 1;
}
/* test and proof */
function test($value)
{
printf("Testing [%s] : %d decimals\n", $value, numberOfDecimals($value));
}
foreach(array(1, 1.1, 1.22, 123.456, 0, 1.0, '1.0', 'not a number') as $value)
{
test($value);
}
Outputs:
Testing [1] : 0 decimals
Testing [1.1] : 1 decimals
Testing [1.22] : 2 decimals
Testing [123.456] : 3 decimals
Testing [0] : 0 decimals
Testing [1] : 0 decimals
Testing [1.0] : 0 decimals
Testing [not a number] : 0 decimals
I have a 50% solution to your question, I will try and write the other half later if I have time:
function num_decimals($number) { if(is_int($number)) return 0; throw new Exception("TODO"); }