Mongoose increment erroneously after several times

I have a collection of products in MongoDB. An application running Express 3 and Mongoose. I am involved in auctions, and when I try to increase the price of a product by 0.01, it works fine up to the 6th time, then switches to "1000.0699999999999" instead of 1000.07. Any idea why? After a few clicks it will be: 1000.1699999999998, etc.

Here is my update function:

app.post('/auctions/add', function(req, res){

  //Get username
  var user = req.session.username ;

  //Product ID from form
  var productID = req.body.product_id ;

  //Find and update product
  //Products.update( { id: productID }, { price: this.price + 0.01 } ).exec() ;
  Products.update( { id: productID }, {$inc: { price: .01 }, user_bidding: { username: user, timeBid: new Date() }}, function(err, numberAffected, raw) {

    console.log(err);
    console.log(numberAffected);
    console.log(raw);

  } ) ;

  //redirect to home
  res.redirect( '/' );

}) ;
+1
source share
2 answers

. javascript... javascript 0.1 + 0.2 !== 0.3.. , (, , , ).. .. , , , ..

.

(0.1 * 10 + 0.2 * 10)/10 === 0.3

-

var price = 1000; 
price = (price*100 + 0.01*100)/100 // => 1000.01;

EDIT:

btw ..

+2

, price.toFixed(3) - . , .

0

Source: https://habr.com/ru/post/1788395/


All Articles