HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Special Formatting of Numbers

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
formattingnumbersspecial

Problem

I need help formatting numbers in a specific way.

If a number has 3 digits or less, I would like it to remain the same.

If a number has more than three digits, I would like it place a decimal after the third decimal.

For instance:

123 --> Stays the same
1234 --> 123.4
1234567 --> 123.4567


I am using SQL Server and want to UPDATE the value in the table. The value is stored as a numeric.

Solution

Assuming they are all ints and you always want the first three digits to appear before the decimal:

WITH n(r) AS (
  SELECT 123 UNION ALL SELECT 1234 UNION ALL SELECT 1234567
)
SELECT LEFT(r, 3) + CASE 
  WHEN LEN(r) > 3 THEN '.' + SUBSTRING(RTRIM(r),4,38) ELSE '' END 
FROM n;

Code Snippets

WITH n(r) AS (
  SELECT 123 UNION ALL SELECT 1234 UNION ALL SELECT 1234567
)
SELECT LEFT(r, 3) + CASE 
  WHEN LEN(r) > 3 THEN '.' + SUBSTRING(RTRIM(r),4,38) ELSE '' END 
FROM n;

Context

StackExchange Database Administrators Q#19216, answer score: 4

Revisions (0)

No revisions yet.