Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 559
jkupczak Avatar asked Oct 17 '25 17:10

jkupczak


2 Answers

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%
like image 97
Koby Douek Avatar answered Oct 19 '25 07:10

Koby Douek


This should do the trick:

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

You can use it as:

formatAsPercentage(.05) // => "5%"
like image 35
wpcarro Avatar answered Oct 19 '25 07:10

wpcarro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!