Question

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.

Was it helpful?

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!";
}

OTHER TIPS

I think I can't get what I want from number_format so I did this and it works fine :

public function floatNumber($number)
 {
      $number_array = explode('.',$number);
      $left = $number_array[0];
      $right = $number_array[1];
      return number_format($number,strlen($right));
 }

number_format() Example :

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

One another solution using string functions to get the count of digits before and after decimal points

$num = 1234.43214;
$aftDecimal = strlen(substr(strrchr($num, "."), 1));
$befDecimal = strlen($num)- ($aftDecimal+1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top