Raja
Raja

Reputation: 493

Multiiplication in two different Values

i have use the following code snippet in my working scenorio of JavaScript.

var t = 0.000029411764705882354 * 34000;

the result of t is 1 . i want to get the exact multiplication result instead of 1 as

0.9999999999972.

Upvotes: 0

Views: 49

Answers (1)

paxdiablo
paxdiablo

Reputation: 881153

First up, that doesn't evaluate to 1. The expression:

29411764705882354 * 34

(removing multiplication by powers of ten) actually gives you:

1000000000000000036

On top of that, unless you have infinite storage capabilities, no encoding scheme can represent every single number. You'll need to get used to the fact that floating point is, more often than not, an approximation of what you asked for - some numbers can be represented exactly but, in the domain of all reals, they form a vanishingly small section :-)

Having said that, there's a couple of ways around it.

First, you can use a bignum-type library (such as MPIR in C) to give you arbitrary (NOT infinite) precision arithmetic. This will handle most cases okay other than irrationals.

Second, you can continue to use floating point but be aware it's not exact and you may need to print out rounded numbers. For example, 0.9999999999972 rounded to <=11 decimal (NOT significant) digits gives you 1.

Upvotes: 2

Related Questions