0

If I add a table like this in MySQL:

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `value` float NOT NULL,
  PRIMARY KEY (`id`)
);

and add an entry:

INSERT INTO `test` (`value`) VALUES ('123.45');

and do a SUM on it like this:

SELECT SUM( value )
FROM `test` 

why does it return 123.449996948242 and not 123.45?

1

3 Answers 3

2

This is because of floating point inaccuracy. Use DECIMAL data type instead.

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `value` decimal(8,2) NOT NULL,
  PRIMARY KEY (`id`)
);

See this example: SQLFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

Because a floating point number has some precision "problems" about:

  1. precision of your machine (limited number of digit that you can store)
  2. representation error
  3. so on...

Comments

0

Have you tried

SELECT 
      ROUND( SUM(value), 2)
FROM `test` 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.