0

I have tried numerous scripts after 1 hour and half of googling and all have either given me the wrong rounded number or the wrong value altogether. These are two scripts I tried.

FIRST TRY:
    Number.prototype.round = function(p) {
      p = p || 10;
      return parseFloat( this.toFixed(p) );
    };


SECOND TRY:
    function roundNumber(number, decimals) { 
        var newnumber = new Number(number+'').toFixed(parseInt(decimals));
        return  parseFloat(newnumber);
    }

Some Example Outputs that I get from both:

0.22  ->  0.21480000000000005 (bad) should be 21
0.43  -> 0.4284 (good) 43 is right

What am I doing wrong? Any help would be appreciated as this has had me poking for too long.

moeiscool
  • 1,318
  • 11
  • 14

1 Answers1

2

Why not use something like this:

Math.round(yourNumber * 100) / 100;

This will round it to two decimal places, the same question was more or less answered here - Round to at most 2 decimal places (only if necessary)

Here is a small example

function round(num){
    var result = Math.round(num * 100) / 100;
    return console.log(result);
}

round(0.4284);

The Fiddle is here to test: https://jsfiddle.net/ToreanJoel/bLzz2mL8/

Community
  • 1
  • 1
TrojanMorse
  • 642
  • 1
  • 8
  • 16
  • This does not answer the question of why the code does not round as OP expected. – Martin May 11 '15 at 16:50
  • Thank you! I am honestly not sure what was wrong but after using yours it works :/ I'd would give you an upvote but I can't without more rep... but when I do ill come back and upvote :) this worked!! – moeiscool May 11 '15 at 16:59
  • No problem man, and @Martin - I understand your point, I apologise, I tried creating the error and came up with a solution that seemed to work but Ill update my answer soon – TrojanMorse May 11 '15 at 17:04