简体   繁体   中英

What's the easiest way to convert a number to a percentage in JavaScript?

I'm calculating the difference in size of images after they've been resized by the user. I take the images new width and divide it by the natural width. This is the code:

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

The numbers I get as a result can look like the following (and the numbers commented out are what I'd like to convert them to).

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%

Never negative numbers. I need to round these numbers and then convert them into strings represented as percentages. Is there an easy and straightforward way to accomplish this?

You can use Math.round like this:

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

A simple example:

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

This should do the trick:

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

You can use it as:

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

I've used in own project

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

You might do some refactoring for your needs in variable names.

First multiply the number by 100 then use Math.round() to round the result. Finally, add the percent sign:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM