【问题标题】:Cast as decimal in mysql在mysql中转换为十进制
【发布时间】:2014-04-20 08:24:09
【问题描述】:

我有下表结构和数据:

create table sample
(
    id INT(10)
);

INSERT INTO sample
values
(23398),
(98743),
(54734);

现在我想了解mysql中的CAST函数。考虑以下查询:

select 
cast((id/3) as decimal(2,2)) as cast1,
cast((id/3) as decimal(3,2)) as cast2,
cast((id/3) as decimal(4,2)) as cast3,
cast((id/3) as decimal(5,2)) as cast4,
cast((id/3) as decimal(6,2)) as cast5,
cast((id/3) as decimal(7,2)) as cast6,
id/3 as actualId
from sample;

请在SQL Fiddle查看此查询的输出。
我想知道为什么这个查询会给出0.999.99,反之亦然。
谁能解释一下?
提前致谢。

【问题讨论】:

  • 它只是在给定的空间内给你最接近的数字
  • 对于cast((id/3) as decimal(2,2)) as cast1, 转换,0.99 如何成为最接近 23398 的数字?
  • 你期望输出什么?
  • 我只是想了解为什么这种类型转换会给我像0.999.99 这样的结果,反之亦然。
  • 你知道0.99是decimal(2,2)能有的最大数吧?

标签: mysql sql int type-conversion decimal


【解决方案1】:

decimal 是一种接受 2 个参数的类型

十进制(大小,位置):

大小决定数字中有多少位。

位决定小数点右边有多少位。

decimal(2,2) - .00 - 2 位数字都在小数点的右边

当将 (23398 / 3) = 7799.33333333 转换为 declimal(2, 2) 时,它会在最接近所需数字 0.99 的指定空间量中生成一个小数

decimal(3,2) - 0.00 - 3 位数字,其中 2 位在小数点的右边

当将 (23398 / 3) = 7799.33333333 转换为 declimal(3, 2) 时,它会在最接近所需数字 9.99 的指定空间量中生成一个小数

如果所有原始数字都是负数,您将得到 -0.99 和 -9.99,因为它们是分配空间内最接近所需数字的数字

事实上,如果你采用 max double 并尝试将其转换为 int,那么 java 会做类似的事情,你将给出 max int ,它不会靠近 max double

【讨论】:

  • 理想情况下,将 (23398 / 3) = 7799.33333333 转换为十进制 (2, 2),输出应该是 0.77 或 0.78,对吗?那为什么 mysql 将其转换为 0.99 呢?
  • 因为你铸造了它而不是四舍五入
  • 如果有什么我希望它是 0.33
  • 或 9.33 但 0.99 和 9.99 更接近
  • 这只是铸造与舍入的本质。
猜你喜欢
  • 1970-01-01
  • 2011-08-07
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2012-06-17
  • 2022-01-14
相关资源
最近更新 更多