Truncar (no redondear) decimales en SQL Server
Estoy tratando de determinar la mejor manera de truncar o soltar lugares decimales adicionales en SQL sin redondear. Por ejemplo:
declare @value decimal(18,2)
set @value = 123.456
Esto redondeará automáticamente el valor @a 123.46....lo que en la mayoría de los casos es bueno. Sin embargo, para este proyecto no necesito eso. ¿Hay una manera sencilla de truncar los decimales que no necesito? Sé que puedo usar la función left () y convertir de nuevo a un decimal...¿alguna otra manera?
16 answers
select round(123.456, 2, 1)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-10 16:03:13
ROUND ( 123.456 , 2 , 1 )
Cuando el tercer parámetro != 0 trunca en lugar de redondear
Http://msdn.microsoft.com/en-us/library/ms175003 (SQL. 90). aspx
Sintaxis
ROUND (numeric_expression , length [ ,function ] )
Argumentos
numeric_expression Es una expresión de los datos numéricos exactos o aproximados categoría de tipo, excepto para los datos de bits tipo.
longitud Es la precisión a la que se redondeará numeric_expression. length debe ser una expresión de tipo tinyint, smallint o int. Cuando length es un número positivo, numeric_expression se redondea al número de posiciones decimales especificadas por length. Cuando length es un número negativo, numeric_expression se redondea en el lado izquierdo del punto decimal, como se especifica por length.
- función Es el tipo de operación a realizar. la función debe ser tinyint, smallint, o int. Cuando la función se omite o tiene un valor de 0 (predeterminado), numeric_expression se redondea. Cuando se especifica un valor distinto de 0, numeric_expression se trunca.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-02 09:17:30
SELECT Cast(Round(123.456,2,1) as decimal(18,2))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-13 07:04:58
Esta es la forma en que pude truncar y no redondear:
select 100.0019-(100.0019%.001)
Devuelve 100.0010
Y su ejemplo:
select 123.456-(123.456%.001)
Devuelve 123.450
Ahora, si desea deshacerse del cero final, simplemente emítelo:
select cast((123.456-(123.456%.001)) as decimal (18,2))
Devuelve 123.45
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-13 07:02:37
En realidad, cualquiera que sea el tercer parámetro, 0 o 1 o 2, no redondeará su valor.
CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-05 06:40:04
Round tiene un parámetro opcional
Select round(123.456, 2, 1) will = 123.45
Select round(123.456, 2, 0) will = 123.46
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-13 07:03:48
Otro truncado sin solución de redondeo y ejemplo.
Convert 71.950005666 to a single decimal place number (71.9)
1) 71.950005666 * 10.0 = 719.50005666
2) Floor(719.50005666) = 719.0
3) 719.0 / 10.0 = 71.9
select Floor(71.950005666 * 10.0) / 10.0
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-12 23:08:54
¿Quieres el decimal o no?
Si no, utilice
select ceiling(@value),floor(@value)
Si lo haces con 0 entonces haz una ronda:
select round(@value,2)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-14 20:53:37
Esto eliminará la parte decimal de cualquier número
SELECT ROUND(@val,0,1)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-07 11:25:29
Sé que esto es bastante tarde, pero no lo veo como una respuesta y he estado usando este truco durante años.
Simplemente restar .005 de tu ronda de valor y uso (@num, 2).
Su ejemplo:
declare @num decimal(9,5) = 123.456
select round(@num-.005,2)
Devuelve 123.45
Ajustará automáticamente el redondeo al valor correcto que está buscando.
Por cierto, ¿estás recreando el programa desde el espacio de la oficina de la película?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 19:24:59
Intente usar este código para convertir 3 valores decimales después de un punto en 2 lugares decimales:
declare @val decimal (8, 2)
select @val = 123.456
select @val = @val
select @val
La salida es 123.46
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-13 07:03:35
Creo que quieres solo el valor decimal, en este caso se puede utilizar lo siguiente:
declare @val decimal (8, 3)
SET @val = 123.456
SELECT @val - ROUND(@val,0,1)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-07 11:24:35
Otra forma es ODBC TRUNCATE
función:
DECLARE @value DECIMAL(18,3) =123.456;
SELECT @value AS val, {fn TRUNCATE(@value, 2)} AS result
Salida:
╔═════════╦═════════╗
║ val ║ result ║
╠═════════╬═════════╣
║ 123,456 ║ 123,450 ║
╚═════════╩═════════╝
Observación:
Recomiendo usar la función incorporada ROUND
con el 3er parámetro establecido en 1.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 18:44:12
Sé que esta pregunta es muy antigua, pero nadie usó sub-cuerdas para redondear. Esto como ventaja la capacidad de redondear números realmente largos (límite de su cadena en SQL server que suele ser de 8000 caracteres):
SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-27 07:52:26
select convert(int,@value)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-04 15:52:24
Mod(x,1)
es la forma más fácil que creo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-13 07:01:32