Make a percentage number

What is the best way to remove "0." XXX% of the number and make it a percentage? What happens if the number turns out to be int?

var number1 = 4.954848; var number2 = 5.9797; $(document).ready(function() { final = number1/number2; alert(final.toFixed(2) + "%"); }); 
+90
javascript math
Dec 15 '11 at 15:42
source share
7 answers

The percentage is simple:

 (number_one / number_two) * 100 

Nothing special needed

 var number1 = 4.954848; var number2 = 5.9797; alert(Math.floor((number1 / number2) * 100)); //w00t! 
+178
Dec 15 '11 at 15:44
source share
 ((portion/total) * 100).toFixed(2) + '%' 
+49
Jun 03 '16 at 0:51
source share

Best solution where en is English:

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

+25
Nov 20 '16 at 3:18
source share

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

 Math.round(0.123456 * 100) //12 

Here is the jQuery plugin for this:

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

Using:

 alert($.percentage(6, 10)); 
+16
Dec 15 '11 at 15:46
source share

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

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

+2
Dec 02 '16 at 21:37
source share

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

+1
Jan 11 '17 at 22:16
source share

@Xtrem's answer is good, but I think toFixed and makePercentage are widely used. Define two functions, and we can use it everywhere.

 const R = require('ramda') const RA = require('ramda-adjunct') const fix = R.invoker(1, 'toFixed')(2) const makePercentage = R.when( RA.isNotNil, R.compose(R.flip(R.concat)('%'), fix, R.multiply(100)), ) let a = 0.9988 let b = null makePercentage(b) // -> null makePercentage(a) // -> ​​​​​99.88%​​​​​ 
0
Aug 22 '18 at 2:57
source share



All Articles