SQL 中四舍五入到 n 个有效数字 [英] Round to n Significant Figures in SQL

查看:64
本文介绍了SQL 中四舍五入到 n 个有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在 SQL 中将数字四舍五入为 n 个有效数字.所以:

I would like to be able to round a number to n significant figures in SQL. So:

123.456 rounded to 2sf would give 120
0.00123 rounded to 2sf would give 0.0012

我知道 ROUND() 函数,它四舍五入到 n 个小数位而不是有效数字.

I am aware of the ROUND() function, which rounds to n decimal places rather than significant figures.

推荐答案

select round(@number,@sf-1- floor(log10(abs(@number)))) 应该做的把戏!

在您的两个示例上成功测试.

Successfully tested on your two examples.

在@number=0 上调用此函数将不起作用.在使用此代码之前,您应该为此添加一个测试.

Edit : Calling this function on @number=0 won't work. You should add a test for this before using this code.

create function sfround(@number float, @sf int) returns float as
begin
    declare @r float
    select @r = case when @number = 0 then 0 else round(@number ,@sf -1-floor(log10(abs(@number )))) end
    return (@r)
end

这篇关于SQL 中四舍五入到 n 个有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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