tags:

views:

820

answers:

6

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

A: 

You could try casting it to an int, subtracting that from your number and then counting what's left.

Allyn
+2  A: 

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.

David Thomas
I tried changing the sample value to an integer value, and the result says "2". What I'm trying to achieve is a process that will return 0 if the number is an integer, else the number of decimal places
Erwin Paglinawan
When you say 'integer' did your integer have the form '10.00' or '10'?
David Thomas
Its value is 10. I'm expecting different kind of format such as 10, 10.00, 10.000. Based on the format, I will have to know the number of decimal digits used
Erwin Paglinawan
+1  A: 
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
ghostdog74
I guess, this is what I was looking for. Thanks
Erwin Paglinawan
A: 
$decnumber = strlen(strstr($yourstr,'.'))-1
SpawnCxy
+1  A: 
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
Kris
note that php interprets a literal 1.0 in source as integer so when converted to string it does not have decimals. (even if you cast it to float at declaration so `$variable = (float)1.0;` ***does not work***)
Kris
A: 

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");
}
too much php
Oops, i lol'ed at that :)
Kris