math - Why do some rounded JavaScript values round the wrong way? -


i have tried numerous scripts after 1 hour , half of googling , have either given me wrong rounded number or wrong value altogether. these 2 scripts 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 both:

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

what doing wrong? appreciated has had me poking long.

why not use this:

math.round(yournumber * 100) / 100; 

this round 2 decimal places, same question more or less answered here - round @ 2 decimal places (only if necessary)

here small example

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

the fiddle here test: https://jsfiddle.net/toreanjoel/blzz2ml8/


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -