0

So I am trying to load an ecommerce checkout but based on the number a user enters:

var finalAmount = convert_amount( $('#input').val() );

The convert amount is to return the amount * 100 like this:

    function convert_amount( amount ) {
        return ( amount * 100 );
    }

Ok so here's the problem. For most numbers it works ok, but for some that I have tried it doesn't work correctly. If I enter something like 8.32 then it returns 832 which is perfect. I found that if I enter 8.72 then it returns 872.0000000000001. I don't get why it is adding the .0000000000001 onto the number.

Another interesting case is if I put in 8.70 it spits back 869.9999999999999.

It was recommended to me to try doing return ( new Number( amount ) * 100 ); but that still did not do the trick.

The reason this is a major problem is because it makes the ecommerce platform reject the amount, saying it is invalid.

Any idea or experiences with this are greatly appreciated.

Thanks!

Nick Young
  • 176
  • 8
  • Always work in integers when dealing with currency. All prices should internally be represented in pennies. (Times like this make me wish we used Yen...) – Niet the Dark Absol May 12 '14 at 21:16
  • Right, that is basically what I am trying to do. The platform needs the amount in pennies so I need to convert the user entered amount to such a value. I will have to take a look at the article you sent me a link to to see if it answers what I need fully. – Nick Young May 12 '14 at 21:18
  • 1
    It is more reliable to use string methods (check for decimal place and strip it out), but alternatively just use `Math.round(amount*100)`. – Niet the Dark Absol May 12 '14 at 21:19
  • @NiettheDarkAbsol thanks that works perfectly. Keeping the other article bookmarked for further reading. Thanks for such a super fast reply! – Nick Young May 12 '14 at 21:23

0 Answers0