簡體   English   中英

在 JavaScript 中將數字轉換為百分比的最簡單方法是什么?

[英]What's the easiest way to convert a number to a percentage in 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%

從不負數。 我需要對這些數字進行四舍五入,然后將它們轉換為以百分比表示的字符串。 有沒有一種簡單直接的方法來實現這一目標?

您可以像這樣使用Math.round

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

一個簡單的例子:

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

這應該可以解決問題:

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

您可以將其用作:

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

我在自己的項目中使用過

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

您可能會根據您的需要對變量名稱進行一些重構。

首先將數字乘以 100,然后使用Math.round()對結果進行四舍五入。 最后,添加百分號:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM