简体   繁体   English

Oracle SQL-根据条件将小数舍入为2/3

[英]Oracle SQL - Round decimal to 2/3 based on conditon

Hello I have a requirement where I need to round decimals based on the condition: 您好,我有一个要求,我需要根据条件四舍五入小数:

If the first 2 digit after the decimals is not 00 then I need to round it to 2 place, otherwise 3 places. 如果小数点后的前两位数字不是00,则需要将其四舍五入为2,否则为3。

Example: 1.232133342 => ROUND(1.232133342,2) //this will work 示例: 1.232133342 => ROUND(1.232133342,2) //这将起作用

but if the number is 1.00233231213 value should be 1.002 //round to 3 digit 但是如果数字是1.00233231213值应为1.002 //四舍五入到3位数字

if the number is 1.0000223123312 then the value should be 1.00002 如果数字为1.0000223123312则该值应为1.00002

Is there any function? 有功能吗? Any help? 有什么帮助吗?

This rounds to at least two digits, maybe more by counting the number of leading zeros in the fractional part using a RegEx 这四舍五入到至少两位数,或者通过使用RegEx计算小数部分中前导零的数目可能会更多

round(x, greatest(2, length(regexp_substr(x,'\.0*'))))

see db-fiddle 参见db-fiddle

Subtract the floor of the number from the number, and check if it's less than .01 . 从数字中减去数字的底数,然后检查它是否小于.01

CASE WHEN ABS(number) - FLOOR(ABS(number)) < .01 THEN ROUND(number, 3)
     ELSE ROUND(number, 2)
END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM