Home > Database > Mysql Tutorial > How to Truncate, Not Round, Decimal Places in SQL Server?

How to Truncate, Not Round, Decimal Places in SQL Server?

Mary-Kate Olsen
Release: 2025-01-15 07:33:44
Original
804 people have browsed it

How to Truncate, Not Round, Decimal Places in SQL Server?

SQL Server: Precision in Decimal Handling – Truncation vs. Rounding

Accurate decimal calculations in SQL Server often require choosing between truncation and rounding. This guide details the key differences and demonstrates how to truncate decimal values without rounding.

Illustrative Example:

DECLARE @value DECIMAL(18,2);
SET @value = 123.456;
Copy after login

SQL Server automatically rounds @value to 123.46. While suitable for many applications, scenarios exist where rounding is undesirable, necessitating truncation.

Effective Truncation Techniques

1. Leveraging the ROUND Function:

The ROUND function offers a subtle yet powerful feature: a third parameter controlling truncation.

ROUND(123.456, 2, 1);
Copy after login

A non-zero third parameter instructs ROUND to truncate rather than round.

2. Utilizing CAST and CONVERT:

Casting or converting the decimal to an integer type directly truncates the decimal portion:

CAST(@value AS INT);
CONVERT(INT, @value);
Copy after login

3. String Manipulation with SUBSTRING or LEFT:

Extract the desired portion using SUBSTRING or LEFT, then convert back to a decimal:

SUBSTRING(@value, 1, 4);
LEFT(@value, 4);
Copy after login

4. Employing the FLOOR Function:

The FLOOR function, combined with multiplication and division, provides another truncation method:

FLOOR(@value * 100) / 100;
Copy after login

This effectively truncates to two decimal places. Remember to adjust the multiplier and divisor for different precision levels.

The above is the detailed content of How to Truncate, Not Round, Decimal Places in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template