SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Thread: Math Problems

  1. #1
    SitePoint Addict
    Join Date
    May 2007
    Posts
    242
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Math Problems

    Hello. 3*0.1 returns 0.30000000000000004. But I rather expect 0.3 for return. How can I change this behaviour?

    And also I want to get logarithm of 100 to the common base 10 as 2. Math.log(100) didnt help.

    Thanks in advance.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    You expect 0.3 but javascript uses floating point maths. This is a common issue, especially when people want to do currency calculations.

    You can either round the resulting number using the toFixed method, or multiple things up until the fraction is gone, perform the math then divide back.

    Code javascript:
    var bad = 3 * 0.1;
    var fixed = (3 * 0.1).toFixed(2);
    var currency = 3 * (0.1 * 100) / 100
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    alert(Math.log(100) * Math.LOG10E);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •