Search code examples
phpfunctiondoubledigits

How to specify number of digits in a float number in php?


The number is: 1234.56789 or maybe '-1234.56789'

What is the php function to specify we have 4 digits before . and 5 digits after . ?

Something like this:

intNumber(1234.56789);   //4
floatNumber(1234.56789); //5

Edit: Actually I want to check if this number has 4 digits before (.) and 5 digits after (.). If yes I save it to database, and if not, I don't save it in the database.


Solution

  • Make use of the round() in PHP with an extra parameter called precision.

    <?php
    echo round(1234.56789,4); //"prints" 1234.5679
                        //^--- The Precision Param
    

    EDIT :

    Thanks a lot. Actually I want to check if this number has 4 digits before (.) and 5 digits after (.). If yes I save it to database, and if not, I don't save it in the database.

    This one is a bit hacky though..

    <?php
    
    function numberCheck($float)
    {
        $arr=explode('.',$float);
        if(strlen(trim($arr[0],'-'))==4 && strlen($arr[1])==5)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    
    if(numberCheck(1234.56789))
    {
        echo "You can insert this number !";
    }
    else
    {
        echo "Not in the correct format!";
    }