【问题标题】:Transforming comma to number and limiting to 3 decimal places将逗号转换为数字并限制为 3 位小数
【发布时间】:2016-03-15 12:58:57
【问题描述】:

我的价值观结构如下:

0,132
6,0999999999999999E-2

我希望它变成这样:

0.132
0.060

在 oracle db 中使用 sql 查询?

把逗号变成点并且只保留 3 个小数点。尝试使用格式设置 CAST 和 TO_NUMBER,但没有成功。

【问题讨论】:

  • 你的原始数据是什么数据类型?

标签: sql oracle11g oracle-sqldeveloper


【解决方案1】:

您可以像这样使用 ORACLE 的 to_number、replace 和 round 函数:

SELECT round(to_number(replace(string,',','.')),3) FROM dual

【讨论】:

    【解决方案2】:

    您还可以使用the to_number() function 的可选第三个参数来指定逗号作为小数分隔符。使用 CTE 提供您的字符串值:

    with t (str) as (
      select '0,132' from dual
      union all select '6,0999999999999999E-2' from dual
    )
    select to_number(str, '9D9999999999999999EEEE', 'NLS_NUMERIC_CHARACTERS='',.''')
      as num
    from t;
    
          NUM
    ----------
          .132
          .061
    

    格式模型需要在小数点分隔符后有足够多的数字,以确保表格中最精确的数字。 EEEE format 处理科学记数法。

    然后您可以使用round()trunc() 限制为小数点后三位;舍入与您的样本值没有区别,但截断表明第二个值从 0.061 变为 0.060:

    with t (str) as (
      select '0,1322' from dual
      union all select '6,0999999999999999E-2' from dual
    )
    select trunc(to_number(str, '9D9999999999999999EEEE',
      'NLS_NUMERIC_CHARACTERS='',.'''), 3)  as num
    from t;
    
           NUM
    ----------
          .132
           .06
    

    如果您愿意,可以使用to_char()(或您的客户端/应用程序)显示前导零和尾随零。

    您也可以将会话 NLS_NUMERIC_CHARACTERS 设置为 ',.',但更安全的是不要假设运行此查询的任何人都会有特定设置并将其作为查询的一部分。

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 2019-01-04
      • 2022-01-22
      • 2015-01-25
      • 1970-01-01
      相关资源
      最近更新 更多