-1

Possible Duplicate:
Elegant workaround for JavaScript floating point number problem

I would like to know how we can convert the following value to a percentage in javascript?

First Expected Output

 Input Value   :  0.03222772304422584
 Expected Value:  0.03  

Second Expected Output

 Input Value   :  0.03222772304422584
 Expected Value:  .03  

Thanks in advance,

Kathir

Community
  • 1
  • 1
Kathir
  • 497
  • 2
  • 6
  • 14
  • 1
    See [this question](http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem), or search Stack Overflow for "floating point" "rounding" "javascript" (http://www.google.com/?q=site:stackoverflow.com%20floating%20point%20javascript%20rounding). It's a very common problem. – Matt Jul 09 '12 at 09:52
  • This one maybe work - Math.round (0.322277230442254 * 100) / 100 – Tom Jul 09 '12 at 09:53
  • 2
    *"First...Expected Value: 0.03 / Second...Expected Value: .03"* Okay, what governs whether there should be a leading 0? – T.J. Crowder Jul 09 '12 at 09:54
  • What do you mean by "*percentage*"? Both your numbers would be *3%*. – Bergi Jul 09 '12 at 10:10

2 Answers2

6

You can use toFixed() and slice() like:

var n = +"0.0322277230442258"; //converts String to Number
var r = n.toFixed(2); // returns 0.03

var r2 = r.slice(1): // returns .03 by removing the first character
m90
  • 11,434
  • 13
  • 62
  • 112
4
var val = "0.03222772304422584";

(+val).toPrecision(1);  // 0.03
(+val).toPrecision(1).slice(1);  // .03

ref.: MDN .toPrecision()

jAndy
  • 231,737
  • 57
  • 305
  • 359