Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 472
user111671 Avatar asked Dec 18 '13 22:12

user111671


People also ask

What is the toFixed () function used for?

Description. toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

Does toFixed round JavaScript?

Note. The toFixed() method will round the resulting value if necessary. The toFixed() method will pad the resulting value with 0's if there are not enough decimal places in the original number. The toFixed() method does not change the value of the original number.

What is decimal point in JavaScript?

In JavaScript, you can use the toFixed() method to limit the decimal places of a number. However, sometimes this method does not give accurate results. It falsely rounds the number down to 1.000 instead of correctly rounding it up to 1.001. This is where other ways to round numbers in JavaScript are useful.


3 Answers

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
like image 104
cassiodoroVicinetti Avatar answered Sep 18 '22 09:09

cassiodoroVicinetti


Have you tried this:

round(2.4232, 2);

This would give you an answer of 2.42.

More information can be found here: http://php.net/manual/en/function.round.php

like image 32
Shafiq Jetha Avatar answered Sep 17 '22 09:09

Shafiq Jetha


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
like image 30
Dănuț Mihai Florian Avatar answered Sep 20 '22 09:09

Dănuț Mihai Florian