This question already has an answer here:

- Is floating point math broken? 14 answers

So I am making a script that adds two numbers (decimal numbers) together, which I have encountered a problem.

http://jsfiddle.net/DerekL/esqnC/

I made the script, it turns out pretty good:

```
0.1 + 0.5 //0.6
0.2 + 0.3 //0.5
```

But soon I see:

```
0.1 + 0.2 //0.30000000000000004
0.01 + 0.06 //0.06999999999999999
```

And it does not look right to me. I know it is a "bug" of computer languages, but I can't find a way to fix that.

```
Math.ceil //No
Math.floor //No
.slice //No
```

**UPDATE**

Is it possible to multiply the numbers by 1000 first, then add them then divide it by 1000?

Use `toFixed`

to convert it to a string with some decimal places shaved off, and then convert it back to a number.

```
+(0.1 + 0.2).toFixed(12) // 0.3
```

It looks like IE's `toFixed`

has some weird behavior, so if you need to support IE something like this might be better:

```
Math.round((0.1 + 0.2) * 1e12) / 1e12
```

```
function add(){
var first=parseFloat($("#first").val());
var second=parseFloat($("#second").val());
$("#result").val(+(first+second).toFixed(2));
}
```

This is common issue with floating points.

Use `toFixed`

in combination with `parseFloat`

.

Here is example in JavaScript.

Testing this Javascript:

```
var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];
var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
sum += arr[i];
}
alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );
```

Dont use `Math.round( (## + ## + ... + ##) * 1e12) / 1e12`

Instead, use `( ## + ## + ... + ##).toFixed(5) )`

In IE 9, `toFixed`

works very well.

Similar Questions

I would like to fetch some decimal numbers from a string which I receive from a remote service. My issue is that I only want decimals in the string prefixed with either + or -. Here is my current

Possible Duplicate: How to force a sign when formatting an Int in c# Format number with + and - sign I would like to sign numbers when there are positive or negative (c#): text = cname + + Strin

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits. function

I'm trying to design a script that given any arbitrary command-line input in euros and cents, calculate the change, using the minimum number of notes or coins. The script works fine with numbers with

This question already has an answer here: Java Generics and adding numbers together 5 answers I want to define a method to make sums between different type numbers: <T> void add (T one, T

This question already has an answer here: Elegant workaround for JavaScript floating point number problem 24 answers In javascript console type in 79.99 * 100 instead of 7999 we get 7998.999999

Possible Duplicate: Why does Javascript getYear() return 108? Javascript date.getYear() returns 111 in 2011? var testDate=new Date(Wed Dec 07 00:00:00 PST 2011) testDate.getYear(); for the above

Possible Duplicate: jQuery: rounding numbers to 2 digits after comma While printing out a number in JavaScript, I only want keep only three digits after the decimal point. The code I am using shows

Possible Duplicate: how to print number with commas as thousands separators in Javascript I have a function that will add thousand seperators to a number, however it is not working well when a decim

Possible Duplicate: A comprehensive regex for phone number validation Perhaps a forgiving JavaScript solution would only make sure that only valid characters are allowed. (digits, dashes, periods, l

I'm writing a program that takes an integer named decimalInput (currently a literal for testing purposes) and converts it to a String called binaryOutput, which is the decimal number in binary form. I

I've seen various sites using the built in wordpress comment system with a custom callback (to generate their own html different than that if the built in comments in wordpress) adding numbers to comm

I seem to be having and issue with the decimal option in access 2010. The images below demonstrate the problem that I am having, one image shows normal 0's in empty cells within Access 2010, however w

I need a validation RegEx for decimal. It should allow up to 5 digits after decimal. Allow: 1 1.0 12.0 12.01 123.01 1,123.01 1,123.013 21,123.01234 3,21,123.01234 How Can I do regex for this?

I came across this problem. It adding numbers using parseFloat or parseInt. IF textbox1 value is 4 and textbox2 value is 2 then i got output as (see script) My doubt is why in addition alone parseFl

This question already has an answer here: JavaScript Regex, where to use escape characters? 3 answers I am having a small issue with placing a RegExp pattern inside a string, I have 2 patterns

Possible Duplicate: Is JavaScript's Math broken? Why can't decimal numbers be represented exactly in binary? What will be result of next code: if(0.3 == ( 0.1 + 0.1 + 0.1 )) { alert(true); } else {

I read on the MDN Reintroduction to JavaScript that JavaScript numbers are a floating point precision type only, and that there are no integers in JavaScript. Yet JavaScript has two functions, parseIn

Using JSONObject to read a json response from a server. The server returns some decimal number. Normal numbers are not a problem to but the problem occurs when there is decimal number of form 0.00068.

is there a way of formatting a string to show whole numbers of a decimal number if it follows 00. example show 10 if number is 10.00. but show 10.2 if number is 10.2 this is for c#, asp.net

I have a requirement to make a decimal textbox (Money textbox) which: only allows numbers 0-9 (allow upper numpad keys 0-9 and right numpad keys 0-9); allows only one dot which don't appear on start.

INTRODUCTION AND RELEVANT INFORMATION: I have an edit control that should accept only signed decimal numbers-something like -123.456. Also, it should be locale aware, since decimal separator is not th

I want to format BigDecimal Numbers with comma and 2 decimal points. e.g. Amount is: 5.0001 and formatted to: 5.00 Amount is: 999999999.999999 and formatted to: 999,999,999.99 Amount is: 1000.4999 an

This question already has an answer here: C# Check if a decimal has more than 3 decimal places? 11 answers I want to check if a decimal has a value in the 4th significant figure. //3 Significan

Easy question: I'm trying to add a number to an array like this: sorted[4][2]+=nbrMvt[i]; but it adds the two numbers as if they were strings. The output just puts the numbers one beside the other...

i am trying adding numbers like this $ctr = 0.0000001 + 0.0000001+ 0.0000001+ 0.0000001+ 0.0000001+ 0.0000001; echo floatval($ctr); it gives result like this 2.0E-5 i have tried, number_format, round

Possible Duplicate: Regular expression for decimal number The column of my table having numeric(18,3) datatype.So I created the validation Expression like this Exp: ^\d+([\.][0-9]{0,3})?$ .Is it r

This question already has an answer here: Truncate (not round off) decimal numbers in javascript 12 answers Im trying to get a number with precision to 2 decimals, for example this is what I wa

There are many inbulit functions like int(octal) which can be used to convert octal numbers into decimal numbers on command line but these doesn't work out in script . int(0671) returns 0671 in script

This question already has an answer here: JavaScript displaying a float to 2 decimal places 3 answers So I made this quick script that calculates some numbers, but the answer ends with many dec

How to restrict the number of digits after the decimal point using onkeyup even in javascript? I want to restrict the number of digits after the decimal point based on an input already given in the

each of the urls displays a number, but when i echo out $z it displays 0 instead of the large group of all the numbers combined... what am i doing wrong? <?php $a = <script type=\text/javascr

Possible Duplicate: Generating random numbers in Javascript in a specific range? Say I wanted to generate a random number from 50 to 100. I know there's: Math.random() but I could only find ways to

This question already has an answer here: Regular Expression to accept only positive numbers and decimals 3 answers In my phonegap app I need to validate the textbox with regular expression whi

This question already has an answer here: Javascript Binding Issue 3 answers Here is my code: var timer = { i: Hello, start: function() { var self = this; window.setInterval(self.tick, 1000);

Possible Duplicate: What's wrong with this division? If you divide 2 / 3, it should return 0.66666666666666667. Instead, I get 0.0 in double value type and 0 in decimal. My purpose is to divide even

So I am trying to add a decimal point in front of a whole in (10) The issue is I'm trying to use sprintf(); but it seems to not be working for me :(. Code: sprintf(.,($percentamount)); Let me know

I have an issue in wpshop plugin in wordpress when I set the price in product $23.99 , the output will be come $23,99. the decimal point turn into comma, someone says that the code is a french code. H

Possible Duplicate: How to add two numbers of any length in java? can anyone help me with this? what i need to do is to add a very large number that a calculator doesn't hold. this is the code i hav

Possible Duplicate: Convert an integer to binary without using the built-in bin function how do I convert a decimal number into a binary list. For example, how do I change 8 into [1,0,0,0]

Sub BatchCopyTextNewColumn() Dim LastRow As Integer 'Variables declared as per Solution from http://stackoverflow.com/questions/24967189 /vba-'decimal-issue-after-replacing-a-hyphen-with-dot 'by Jagad

I am trying to print the numbers simply in the sequence i.e 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 using Loop, First i converted each number into Hexa printed it reset it to the decimal in

Possible Duplicate: valign not working on a td? I'm adding rows to a table dynamically using javascript as following: var lastRow = tbl.rows.length; var iteration = lastRow; var row = tbl.insertRow(

I am loading numeric values to 2 decimal places using Javascript. All values seem okay, apart from £299.90 and £499.90, which loads as £299.9 and £499.9 Current code: //ROUNDING FUNCTION function roun

I want to know what a regex would look like for: only whole numbers only numbers with less than or equal to two decimal places (23, 23.3, 23.43)

I need to use an accurate number that has many decimal places. If I use the type decimal (because float is not precise enough to store such numbers) I can have something like 0.003352466 and it is pre

I was wondering how to make avg in the following program round to 3 decimal places: public class BaseballCalculator { public static void main(String args[]) { Scanner myScanner = new Scanner(System.i

This question already has an answer here: IE background size not working 3 answers I am trying to use javascript to setup background image size. I have image.style.backgroundSize = 133+'px '+1

Possible Duplicate: Extract decimal part from a floating point number in C I would like retrieve the decimal part of a double in the most efficient way. Something like this: double a = 1.5; double

Possible Duplicate: Convert DB2 SQL Decimal to DATE I have a db2 database and I want to convert a decimal to a date during the where clause in a select statement. The decimal date could be 12 or 13