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%"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With