在 oracle 中四舍五入到第一位数字 +1
Rounding to first digit +1 in oracle
我有一列如下,我想要的输出如下所示。 Col1 是数字数据类型。
Col1 OutputCol1
1234 round to 2000
2300000 round to 3000000
456789.23 round to 500000
总是第一个数字+1。我可以使用带负值的 round 函数,但如果第二个数字小于 5,它会四舍五入到更低。
嗯。 . .您可以将 1 添加到第一个数字,然后用零填充:
select rpad(cast(substr(col1, 1, 1) as int) + 1,
log(10, col1),
'0'
)
这里有两种方法 - 一种是数学方法,另一种是使用科学记数法对 col1 的字符串输出进行操作:
WITH sample_data AS (SELECT 1234 col1 FROM dual UNION ALL
SELECT 2300000 col1 FROM dual UNION ALL
SELECT 456789.23 col1 FROM dual UNION ALL
SELECT -183 col1 FROM dual UNION ALL
SELECT 1000 col1 FROM dual UNION ALL
SELECT 0.392 col1 FROM dual)
SELECT col1,
ceil(col1 / order_of_magnitude_of_col1) * order_of_magnitude_of_col1 output1,
CEIL(to_number(SUBSTR(sn, 1, 4))) * POWER(10, to_number(SUBSTR(sn, 6))) output2
FROM (SELECT col1,
power(10, floor(LOG(10, abs(col1)))) order_of_magnitude_of_col1,
to_char(col1, 'fms0.0EEEE') sn
FROM sample_data);
COL1 OUTPUT1 OUTPUT2
---------- ---------- ----------
1234 2000 2000
2300000 3000000 3000000
456789.23 500000 500000
-183 -100 -100
1000 1000 1000
0.392 0.4 0.4
使用字符串操作。取第一个数字,加一个,添加尾随零。如果数字后面仅跟有零(1000 或 10.00),则不要加 1。
select col1,
case when nvl(to_number(substr(to_char(col1), 2)),0) = 0 then
to_number(rpad(substr(to_char(trunc(col1)), 1, 1), length(to_char(trunc(col1))), '0'))
else
to_number(rpad(to_char(to_number(substr(to_char(trunc(col1)), 1, 1)) + 1), length(to_char(trunc(col1))), '0'))
end as x,
to_number(substr(to_char(trunc(col1)), 2))
from
我有一列如下,我想要的输出如下所示。 Col1 是数字数据类型。
Col1 OutputCol1
1234 round to 2000
2300000 round to 3000000
456789.23 round to 500000
总是第一个数字+1。我可以使用带负值的 round 函数,但如果第二个数字小于 5,它会四舍五入到更低。
嗯。 . .您可以将 1 添加到第一个数字,然后用零填充:
select rpad(cast(substr(col1, 1, 1) as int) + 1,
log(10, col1),
'0'
)
这里有两种方法 - 一种是数学方法,另一种是使用科学记数法对 col1 的字符串输出进行操作:
WITH sample_data AS (SELECT 1234 col1 FROM dual UNION ALL
SELECT 2300000 col1 FROM dual UNION ALL
SELECT 456789.23 col1 FROM dual UNION ALL
SELECT -183 col1 FROM dual UNION ALL
SELECT 1000 col1 FROM dual UNION ALL
SELECT 0.392 col1 FROM dual)
SELECT col1,
ceil(col1 / order_of_magnitude_of_col1) * order_of_magnitude_of_col1 output1,
CEIL(to_number(SUBSTR(sn, 1, 4))) * POWER(10, to_number(SUBSTR(sn, 6))) output2
FROM (SELECT col1,
power(10, floor(LOG(10, abs(col1)))) order_of_magnitude_of_col1,
to_char(col1, 'fms0.0EEEE') sn
FROM sample_data);
COL1 OUTPUT1 OUTPUT2
---------- ---------- ----------
1234 2000 2000
2300000 3000000 3000000
456789.23 500000 500000
-183 -100 -100
1000 1000 1000
0.392 0.4 0.4
使用字符串操作。取第一个数字,加一个,添加尾随零。如果数字后面仅跟有零(1000 或 10.00),则不要加 1。
select col1,
case when nvl(to_number(substr(to_char(col1), 2)),0) = 0 then
to_number(rpad(substr(to_char(trunc(col1)), 1, 1), length(to_char(trunc(col1))), '0'))
else
to_number(rpad(to_char(to_number(substr(to_char(trunc(col1)), 1, 1)) + 1), length(to_char(trunc(col1))), '0'))
end as x,
to_number(substr(to_char(trunc(col1)), 2))
from