Floating Point Math

Your language isn't broken, it's doing floating point math. Computers can only natively store integers, so they need some way of representing decimal numbers. This representation comes with some degree of inaccuracy. That's why, more often than not, .1 + .2 != .3.

Below are some examples of sending .1 + .2 to standard output in a variety of languages.

read more: | wikipedia | IEEE 754 | Stack Overflow

Language Code Result
PHP echo .1 + .2; 0.3
MySQL SELECT .1 + .2; 0.3
Erlang io:format("~w~n", [0.1 + 0.2]). 0.30000000000000004
Ruby puts 0.1 + 0.2 0.30000000000000004
Ruby supports rational numbers via: Rational.
Ruby also has a library specifically for decimals: BigDecimal.
Python print(.1 + .2)
And
.1 + .2
0.3
And
0.30000000000000004
Python's "print" method converts 0.30000000000000004 to a string and shortens it to "0.3". To achieve the desired floating point result, use print(repr(.1 + .2)).
JavaScript document.writeln(.1 + .2); 0.30000000000000004
Java System.out.println(.1 + .2); 0.30000000000000004
C# Console.WriteLine(.1 + .2); 0.3
GHC (Haskell) 0.1 + 0.2 0.30000000000000004
Haskell supports rational numbers. To get the math right, (1 % 10) + (2 % 10) returns 3 % 10.
Hugs (Haskell) 0.1 + 0.2 0.3
bc 0.1 + 0.2 0.3
Gforth 0.1e 0.2e f+ f. 0.3
dc 0.1 0.2 + p .3
Racket (PLT Scheme) (+ .1 .2)
And
(+ 1/10 2/10)
0.30000000000000004
And
3/10
Emacs Lisp (+ .1 .2) 0.30000000000000004
Common Lisp * (+ .1 .2)
And
* (+ 1/10 2/10)
0.3
And
3/10
Go package main
import "fmt"
func main() {
  fmt.Println(.1+.2)
}
0.3
Powershell PS C:\>0.1 + 0.2 0.3
Prolog ?- X is 0.1 + 0.2. X = 0.3.
Perl perl -e 'printf q{%.17f}, 0.1+0.2' 0.30000000000000004

I am Erik Wiffin. You can contact me at: erik.wiffin.com or erik.wiffin@gmail.com.

This project is on github. If you think this page could be improved, send me a pull request.