I want to round value of one select
For example:
select width from Home
The result of width
is "3.999999999999999"
I want to be "3.99" or "3.9"
ROUND(width, 1 or 2, 1)
should work best for you. Example:
SELECT CONVERT(NUMERIC(13,2), ROUND(width, 2, 1))
FROM Home
will return 3.99, and
SELECT CONVERT(NUMERIC(13,1), ROUND(width, 1, 1))
FROM Home
will return 3.9
If you want a value of 3.99 or 3.9, then you do not want round()
. You want floor()
. However, that works on integers, but not decimals.
The naive method of cast(width as decimal(10,2))
will return 4.00
, as will round(width, 2)
. One method is to subtract a small amount. So:
select cast(width - 0.005 as decimal(10, 2))
should give you "3.99".
If you need only two decimal values you can multiply by 100, floor the result and divide by 100 (This is necessary because floor works only flooring a number to an integer):
select floor(width * 100) / 100 from Home
Here are the steps
3.99999999 * 100 = 399.999999 --- Multiply by 100
floor(399.999999) = 399 --- floor
399 / 100 = 3.99 --- Divide by 100
It is also possible using a different form of round function with a third parameter .
When the third parameter is different from 0 the result is truncated instead of rounded
Syntax
ROUND ( numeric_expression , length [ ,function ] )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
length
Is the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.
function
Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.
Here is the select using this version of round
:
select round(width, 2, 1) from Home
It's fairly simple, if you want the result 3.9 then
select round(width,1) from Home
If you need the result 3.99 then use..
select round(width,2) from Home
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.