如何在JavaScript中将数字转换为百分比?

3
我正在计算用户调整大小后的图片尺寸差异。我获取图像的新宽度并将其除以原始宽度。这是代码: 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%

不要有负数。我需要将这些数字四舍五入,然后转换为以百分比表示的字符串。是否有一种简单明了的方法来完成这个任务?


看看我的答案,它完美地运行。 - Pavlo Zhukov
4个回答

5
您可以像这样使用Math.round
 Math.round((img.width/ naturalWidth) * 100));

一个简单的例子:

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


2
使用round函数来取整,注意例子1.39402 // 140% - George Mauer
1
Math.floor会返回一个绝对整数,没有必要进行四舍五入。你应该使用其中之一。 - Dinei
为了更清晰,我想实际上我的意思是将 1.39402 更改为 1.39502。前者应该是 139%,而后者应该四舍五入为 140%。 - jkupczak
话虽如此,我认为@GeorgeMauer关于使用round而不是Math.floor是正确的。我的初始打字错误意味着你的答案并不是我真正想要的。你回答得很快,所以如果你编辑它,我会接受你的答案! - jkupczak

3
这应该能解决问题:
const formatAsPercentage = x => `${Math.round(x * 100)}%`

您可以将其用作:

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

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}));
});

你可能需要在变量名中进行一些重构以满足你的需求。


1
首先将数字乘以100,然后使用Math.round()来四舍五入结果。最后,添加百分号:
Math.round(img.width / naturalWidth * 100) + "%";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接