简体   繁体   中英

Mysql ROUND return worng value?

I have a rule table:

rule_id  basic   hra  conveyance  medical
      1    0.5  0.25         800     1250

I run this query:

SELECT ROUND( 16405 ) AS `CTC`, ROUND( 16405 * r.basic ) AS `basic`,
ROUND( 16405 * r.hra ) AS `hra`, r.conveyance AS `conveyance`,
r.medical AS `medical` 
FROM `rule` AS r
WHERE `r`.`rule_id` =1

It returns the following:

CTC     basic   hra conveyance  medical  
16405   8202    4101    800          1250

The value of basic should be 8203 but it returns 8202.

取而代之的ROUND使用CEIL -它会总结你的价值。

CEIL( 16405 * r.basic ) AS  `basic`

These are the rules as explained in the documentation :

  • For exact-value numbers, ROUND() uses the “round half away from zero” or “round toward nearest” rule: A value with a fractional part of .5 or greater is rounded up to the next integer if positive or down to the next integer if negative. (In other words, it is rounded away from zero.) A value with a fractional part less than .5 is rounded down to the next integer if positive or up to the next integer if negative.

  • For approximate-value numbers, the result depends on the C library . On many systems, this means that ROUND() uses the "round to nearest even" rule: A value with any fractional part is rounded to the nearest even integer.

According to your last edit so far, 8202.5 is getting rounded towards zero. That probably means that you are not using an exact data type like DECIMAL . If your column type is FLOAT or DOUBLE , the rounding algorithm is platform-dependent (and you're also subject to floating point precision issues).

You can check whether explicit casting solves the issue:

SELECT ROUND(8202.5), ROUND(CAST(8202.5 AS DECIMAL))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM