在mysql中将浮点数转换为十进制 [英] casting a floating to decimal in mysql

查看:55
本文介绍了在mysql中将浮点数转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解这里的 cast 函数和 decimal.decimal(7,2) 实际上是什么意思?.函数的第一部分和第二部分arg.

I am not quite understanding the cast function and decimal here. What does decimal(7,2) actually mean?. The first part and the second part arg of the function.

为什么我需要在此处cast/convert我的浮点数到十进制?

Why do i need to cast/convert my floating point to decimal here?.

mysql> SELECT productCode, MAX(price), MIN(price),
              CAST(AVG(price) AS DECIMAL(7,2)) AS `Average`,
              CAST(STD(price) AS DECIMAL(7,2)) AS `Std Dev`,
              SUM(quantity)
       FROM products
       GROUP BY productCode;
+-------------+------------+------------+---------+---------+---------------+
| productCode | MAX(price) | MIN(price) | Average | Std Dev | SUM(quantity) |
+-------------+------------+------------+---------+---------+---------------+
| PEC         |       0.49 |       0.48 |    0.49 |    0.01 |         18000 |
| PEN         |       1.25 |       1.23 |    1.24 |    0.01 |         15000 |
+-------------+------------+------------+---------+---------+---------------+

下面是相同的 sql 小提琴?.

Below is a sql fiddle for the same?.

http://sqlfiddle.com/#!2/1ed51b/1/0

我的问题再次重复:

  1. decimal(7,2) 实际上是什么意思?.第一部分和函数的第二部分 arg.
  2. 为什么我需要在此处强制转换/转换我的浮点到十进制?
  1. What does decimal(7,2) actually mean?. The first part and the second part arg of the function.
  2. Why do i need to cast/convert my floating point to decimal here?.

推荐答案

DECIMAL(7,2) 表示一个固定小数点的数字,一共有 7 位,其中 2 位到小数点右边.(所以,左 5 个,右 2 个.)

DECIMAL(7,2) means a number with a fixed decimal point, having 7 digits altogether, with 2 of them to the right of the decimal point. (So, 5 left, 2 right.)

除非您想要 DECIMAL 类型的行为(通常是定点)而不是 FLOAT 类型的行为(有用的近似值,其右边的位数相对不可预测,否则您不需要进行强制转换)小数点).例如,您的产品代码PEC" 的平均值是 33333.65;没有演员表是 33333.653333.

You don't need to cast unless you want the behavior of DECIMAL types (typically, fixed point) rather than the behavior of FLOAT types (useful approximations with a relatively unpredictable number of digits right of the decimal point). For example, your average for product code "PEC" with the cast is 33333.65; without the cast it's 33333.653333.

如果您经常使用所有数字,您可能应该增加演员表中的数字总数.比如说,对于 DECIMAL (14,2) 之类的东西.

If you're routinely using all the digits, you should probably increase the total number of digits in the cast. Say, to something like DECIMAL (14,2).

这篇关于在mysql中将浮点数转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆