Division of a float/integer by a integer in jquery

2019-08-04 00:51发布

This question already has an answer here:

I am dividing a number( may be in amount format of XX.XX) by a integer.

But when i do 6.6 / 6 or 3.3/3 , it gives 1.099999... , instead of 1.1.

What i am doing is, I am dividing the amount equally among the number of people and if any remainder amount exists, I am adding that extra amount to one person among them.

May be something of this kind, 104/6 will be divided as 17.85, 17.83, 17.83, 17.83, 17.83, 17.83 [ May not be accurate, just for illustration].

JS Bin link ----> http://jsbin.com/amileg/1/edit

Kindly help me in getting the right calculation logic.

Thanks!!

2条回答
贪生不怕死
2楼-- · 2019-08-04 01:17

That is floating point arithmetic and those are rounding errors . You can read this for more.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

All numbers in JavaScript are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits. They do not always exactly represent real numbers, including fractions.

查看更多
3楼-- · 2019-08-04 01:21

You can use .toFixed()

var res = (vall / tot).toFixed(2);
//input `6.6/6`: , output : `1.10`

Demo ----> http://jsbin.com/amileg/4/edit

查看更多
登录 后发表回答