SQL sql中的to_number函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8310644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:27:17  来源:igfitidea点击:

to_number function in sql

sqloracleoracle11g

提问by dato datuashvili

i could not understand why following code SQL>

我不明白为什么下面的代码 SQL>

Select to_number('1234.64', '9999.9') from Dual;

returns this number 1234.6?is it something like rounding ,truncation or?please help me to understand this code,i know to_number functions,i have used many times this code for simple chars,but here it is not clear anything

返回这个数字 1234.6?它是像四舍五入、截断还是类似的东西?请帮助我理解这段代码,我知道 to_number 函数,我已经多次使用这个代码来处理简单的字符,但这里什么都不清楚

回答by

This looks a lot like Oracle, but I suspect that the result would be similar in any SQL that used to_number.

这看起来很像 Oracle,但我怀疑结果在任何使用 to_number 的 SQL 中都会相似。

The to_number function takes two arguments: the string to be converted to a number, and the format string for the conversion.

to_number 函数接受两个参数:要转换为数字的字符串和用于转换的格式字符串。

In the example, '12345.64' is the string to be converted, while '9999.9' is the format string. In this format string, a 9 stands for a digit while a . stands for the decimal point.

在示例中,'12345.64' 是要转换的字符串,而 '9999.9' 是格式字符串。在此格式字符串中,9 代表数字,而 . 代表小数点。

So the function is asking to convert the string '12345.64' to a number with up to 4 digits to the right of the decimal point, and only 1 digit after the decimal point.

因此,该函数要求将字符串'12345.64' 转换为小数点右侧最多4 位且小数点后仅1 位的数字。

The second argument is optional - under normal circumstances, I would omit it.

第二个参数是可选的——在正常情况下,我会省略它。

回答by Marco

You should use

你应该使用

SELECT to_number('1234.64', '9999.99') from Dual;

Your mask tells engine you want just one decimal, so number gets rounded.
If you want to get exact number, don't specify any mask:

您的掩码告诉引擎您只需要一位小数,因此数字会四舍五入。
如果你想得到确切的数字,不要指定任何掩码:

SELECT to_number('1234.64') from Dual;