Make a number a percentage

JavascriptMath

Javascript Problem Overview


What's the best way to strip the "0."XXX% off a number and make it a percentage? What happens if the number happens to be an int?

var number1 = 4.954848;
var number2 = 5.9797;

$(document).ready(function() {    
    final = number1/number2;
    alert(final.toFixed(2) + "%");
});

Javascript Solutions


Solution 1 - Javascript

A percentage is just:

(number_one / number_two) * 100

No need for anything fancy:

var number1 = 4.954848; var number2 = 5.9797;

alert(Math.floor((number1 / number2) * 100)); //w00t!

Solution 2 - Javascript

((portion/total) * 100).toFixed(2) + '%'

Solution 3 - Javascript

The best solution, where en is the English locale:

fraction.toLocaleString("en", {style: "percent"})

Solution 4 - Javascript

Well, if you have a number like 0.123456 that is the result of a division to give a percentage, multiply it by 100 and then either round it or use toFixed like in your example.

Math.round(0.123456 * 100) //12

Here is a jQuery plugin to do that:

jQuery.extend({
    percentage: function(a, b) {
        return Math.round((a / b) * 100);
    }
});

Usage:

alert($.percentage(6, 10));

Solution 5 - Javascript

Most answers suggest appending '%' at the end. I would rather prefer Intl.NumberFormat() with { style: 'percent'}

var num = 25;

var option = {
  style: 'percent'

};
var formatter = new Intl.NumberFormat("en-US", option);
var percentFormat = formatter.format(num / 100);
console.log(percentFormat);

Solution 6 - Javascript

Numeral.js is a library I created that can can format numbers, currency, percentages and has support for localization.

numeral(0.7523).format('0%') // returns string "75%"

[tag:numeral.js]

Solution 7 - Javascript

var percent = Math.floor(100 * number1 / number2 - 100) + ' %';

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1040259View Question on Stackoverflow
Solution 1 - JavascriptNaftaliView Answer on Stackoverflow
Solution 2 - JavascriptxtremView Answer on Stackoverflow
Solution 3 - JavascriptLiron ShapiraView Answer on Stackoverflow
Solution 4 - JavascriptAlex TurpinView Answer on Stackoverflow
Solution 5 - JavascriptStangSpreeView Answer on Stackoverflow
Solution 6 - JavascriptadamwdraperView Answer on Stackoverflow
Solution 7 - JavascriptTomas KubesView Answer on Stackoverflow