From @manix and @Matt Crandall's suggestions, I found out that .toFixed(2) solves my problem. I'll dig deeper into the why later. Case closed.
I'm building a database for a store and get wrong results whenever I get an order of 5 for an item that has .99 as price tag.
SQL code:
DROP DATABASE IF EXISTS store;
CREATE DATABASE store;
USE store;
CREATE TABLE products (
id INT(11) AUTO_INCREMENT NOT NULL,
name VARCHAR(50) NOT NULL,
price DECIMAL(10,2) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO products
(name, price)
VALUES
('Some item', 39.99);
NodeJS code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
port: XXXX,
user: 'XXXX',
password: 'XXXX',
database: 'store'
});
connection.connect((err) => {
if (err) throw err;
totalCost(1, 5);
});
function totalCost(id, quantity) {
connection.query('SELECT price FROM products WHERE id = "' + id + '"', (err, res) => {
if (err) throw err;
var price = res[0].price;
var total = price * quantity;
console.log('Price: $' + price + '\nTotal: $' + total);
});
}
For this example, the total is 199.95000000000002
whilst it should be 199.95
. Why the trailing numbers? How do it fix this?
I'm sorry if this is a duplicate question. I've looked but couldn't find any similar question (maybe I used wrong keywords for my search).