Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Web Programming > JavaScript > Javascript
|
Javascript General Javascript discussions.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Javascript section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old June 13th, 2006, 04:44 AM
Authorized User
 
Join Date: May 2006
Posts: 40
Thanks: 0
Thanked 0 Times in 0 Posts
Default javascript math problem

hi i was doing some work in javascript and found the following error

consider the code
Code:
function fnCalc() {
    var a = 30.01;
    var b = 30.02;

    alert(a + b);//60.03

    var c = 30.01;
    var d = 30.03;

    alert(c + d);//60.040000000000006
}
The first alert gives 60.03 and the second 60.040000000000006
can any one tell me why this happens and how to solve. i faced the same problem with another number but it works for that now

thanks

 
Old June 13th, 2006, 05:36 AM
joefawcett's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 3,074
Thanks: 1
Thanked 38 Times in 37 Posts
Default

You'va come across a limitation of binary, some numbers can't be represented accurately in the same way that denary notation can't represent two thirds.
If you want to stick with JavaScript then you can try converting to integers first, by multiplying by 1,000,000 for instance, and then converting back later.

--

Joe (Microsoft MVP - XML)





Similar Threads
Thread Thread Starter Forum Replies Last Post
Need Help with Math.pow trryan5 Java Basics 4 July 27th, 2007 06:12 AM
Math question dparsons ASP.NET 1.0 and 1.1 Professional 5 June 14th, 2006 02:31 PM
York Math -- regarding... vijayk Wrox Book Feedback 0 February 5th, 2005 06:23 AM
Math problem... help please! Varg_88 Classic ASP Basics 2 September 30th, 2004 05:17 AM
Math problem solved in Java! freezotic BOOK: Beginning Java 2 7 January 21st, 2004 03:40 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.