Dig
Dig

Reputation: 1

javascript fraction to percent

When I tried to convert fraction in Javascript, I am facing a problem. I need to make a fraction value to percent value. a = 0.0175 It should be displayed as 1.75%. I tried to multiply by 100. But I am getting some extra fractions added to the right - 1.7500000000000002 . I just need 1.75, not any more zeroes added to the end.

Thanks in advance.

Upvotes: 0

Views: 6305

Answers (3)

Robert Eisele
Robert Eisele

Reputation: 115

Try this:

function formatNum(n) {
    return Math.round(n * 1e4) / 1e2;
}

var a = 0.0175;
var n = formatNum(a); // 1.75

var b = 0.21;
var m = formatNum(b); // 21

It simply multiplies by 100*100, rounds the result and divides again by 100. The result is still a number and not a string as with the toFixed-approach.

Upvotes: 0

Nik Terentyev
Nik Terentyev

Reputation: 2310

multiply, round and divide:

// rounding to set precision or default precision = 3
function roundToPrecision ( value, precision ) {
  precision = ( typeof precision !== 'undefined' ) ? precision : 3;
  var mult = Math.pow( 10, precision );

  return Math.round( mult * value ) / mult;
}

usage:

var zzz = roundToPrecision( 123.1231232546 ); // 123.123

var aaa = roundToPrecision( 123.1231232546, 1 ); // 123.1

Upvotes: 0

Ali Adravi
Ali Adravi

Reputation: 22733

Try this

var a = 0.0175
var num = a * 100;
var n = num.toFixed(2)

Upvotes: 3

Related Questions