在JavaScript中将数字转换为百分比的最简单方法是什么?

时间:2017-03-20 18:23:20

标签: javascript

我正在计算用户调整大小后图像大小的差异。我将图像新宽度除以自然宽度。这是代码:

Math.round( (img.width / naturalWidth) * 100) / 100

我得到的数字可能如下所示(注释掉的数字是我想将它们转换成的数字)。

0       // 0%
1       // 100%
1.2     // 120%
1.39402 // 139%
1.39502 // 140%
21.56   // 216%
0.4     // 40%
0.44    // 44%
0.1     // 10%
0.01    // 1%
0.005   // 1%
0.0049  // 0%

从不否定数字。我需要对这些数字进行舍入,然后将它们转换为以百分比表示的字符串。有一种简单直接的方法来实现这一目标吗?

4 个答案:

答案 0 :(得分:3)

您可以像这样使用Math.round

 Math.round((img.width/ naturalWidth) * 100));

一个简单的例子:

    var a = 1.2;
    var b = 1;
    
    alert(Math.round((a / b) * 100) + '%');  // 120%

答案 1 :(得分:3)

这应该可以解决问题:

const formatAsPercentage = x => `${Math.round(x * 100)}%`

您可以将其用作:

formatAsPercentage(.05) // => "5%"

答案 2 :(得分:1)

我在自己的项目中使用过

function calculatePercent(config){
    var currentProgressPercent;
    var totalRecords = Number.parseFloat(config.totalRecords);
    var current = Number.parseFloat(config.current);
    currentProgressPercent = 0;
    if (!(isNaN(totalRecords) || isNaN(current))) {
        currentProgressPercent = (totalRecords === 0 ? 100 : Math.round((current / totalRecords) * 100));
    }

    currentProgressPercent += '%';
    return currentProgressPercent;
}

var input = [0, 1, 1.2, 2.156, 0.4, 0.44, 0.1, 0.01, 0.005, 0.0049];
input.forEach(function(value){
     alert(calculatePercent({current:value, totalRecords: 1}));
});

您可以根据变量名称的需要进行一些重构。

答案 3 :(得分:1)

首先将数字乘以100,然后使用Math.round()对结果进行舍入。最后,添加百分号:

Math.round(img.width / naturalWidth * 100) + "%";
相关问题