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.
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.
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.
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.
The exact equivalent command in PHP is function number_format:
number_format($a, 3, '.', ""); // 2.423
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.
More information can be found here: http://php.net/manual/en/function.round.php
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With