javascript PHP 中 JS: something.toFixed() 的确切等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20670114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:00:13  来源:igfitidea点击:

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

javascriptphp

提问by user111671

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.

如果我 a.toFixed(3);在 javascript('a' 等于 2.4232)中有什么是 php 中完全等效的命令来检索它?我搜索了它,但没有找到正确的解释附加到答案中。

采纳答案by D?nu? Mihai Florian

I found that sprintfand number_formatboth round the number, so i used this:

我发现了,sprintf并且number_format都四舍五入,所以我使用了这个:

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

回答by cassiodoroVicinetti

The exact equivalent command in PHP is function number_format:

PHP 中完全等效的命令是函数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
  • 它将数字四舍五入到小数点后第三位
  • 如果需要总是有三个十进制数字,它会用“0”字符填充

Here is a practical function:

这是一个实用的功能:

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

toFixed($a, 3); // 2.423

回答by Shafiq Jetha

Have you tried this:

你有没有试过这个:

round(2.4232, 2);

This would give you an answer of 2.42.

这会给你 2.42 的答案。

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

更多信息可以在这里找到:http: //php.net/manual/en/function.round.php

回答by Jon

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.

一个直接的等价物是sprintf('%.03F', $a)。这会将有问题的值格式化为带有 3 个十进制数字的数字。如果需要,它也会四舍五入。

回答by Aurelio De Rosa

In PHP you can use a function called round.

在 PHP 中,您可以使用一个名为round的函数。

回答by oabarca

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

回答by Afia

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

直接的解决方案是在 php 中使用 number_format()

number_format(2.4232, 3);