What is the exact equivalent of JS: something.toFixed() in PHP?

If I have `a.toFixed(3);` in javascript ('a' being equal to 2.4232) what is the exact equivalent command in php to retrieve that? I searched for it but found no proper explanation appended to the answers.

I found that `sprintf` and `number_format` both round the number, so i used this:

``````\$number = 2.4232;
\$decimals = 3;
\$expo = pow(10,\$decimals);
\$number = intval(\$number*\$expo)/\$expo; //  = 2423/100
``````

The exact equivalent command in PHP is function number_format:

``````number_format(\$a, 3, '.', ""); // 2.423
``````
• it rounds the number to the third decimal place
• it fills with '0' characters if needed to always have three decimal digits

Here is a practical function:

``````function toFixed(\$number, \$decimals) {
return number_format(\$number, \$decimals, '.', "");
}

toFixed(\$a, 3); // 2.423
``````

Have you tried this:

``````round(2.4232, 2);
``````

This would give you an answer of 2.42.

A direct equivalent is `sprintf('%.03F', \$a)`. This will format the value in question as a number with 3 decimal digits. It will also round if required.

In PHP you can use a function called round.

Here is the translation:

``````function toFixed(\$number, \$dec_length){
\$pos=strpos(\$number.'', ".");
if(\$pos>0){
\$int_str=substr(\$number,0,\$pos);
\$dec_str=substr(\$number, \$pos+1);
if(strlen(\$dec_str)>\$dec_length){
return \$int_str.(\$dec_length>0?'.':'').substr(\$dec_str, 0,\$dec_length);
}else{
return \$number;
}
}else{
return \$number;
}
}

//toFixed(1234.678, 0) = 1234
//toFixed(1234.678, 1) = 1234.6
//toFixed(1234.678, 2) = 1234.67
//toFixed(1234.678, 4) = 1234.678
``````

The straight forward solution is to use in php is `number_format()`

``````number_format(2.4232, 3);
``````