Link to home
Start Free TrialLog in
Avatar of Jeff Jones
Jeff Jones

asked on

Format numbers in 2008

Have a random numberic values that needs to be converted to 4 characters.  Depending on the number, the padding of the zero's on either the right or the left will vary.  For instance = a value of 147.8 will be converted to 1478 (decimal point is stripped out).  If the value is 0.9 the converted value needs to be 0009.  However, there could also be an instance where the value is 7.8 and the converted value would be 0780.

If this were in 2012, I think I could use the Format() function, but since that's not an option I need some help in how I can accomplish this as efficiently as possible.
Avatar of PortletPaul
PortletPaul
Flag of Australia image

declare @Table1 table
    ([NumberCol] decimal(12,3))

    
INSERT INTO @Table1
    ([NumberCol])
VALUES
    (0.9),
    (148.134),
    (7.945),
    (12.678)

select case when NumberCol < 10 then right('0000' + REPLACE(CONVERT(varchar(20), (CAST(NumberCol AS money)/10), 1), '.', ''),3) + '0'
                else right('0000' + REPLACE(CONVERT(varchar(20), (CAST(NumberCol AS money)/10), 1), '.', ''),4)
           end
from @Table1

-- or --

select NumberStr
from @Table1
cross apply (
    select case when NumberCol < 10 then right('0000' + REPLACE(CONVERT(varchar(20), (CAST(NumberCol AS money)/10), 1), '.', ''),3) + '0'
                else right('0000' + REPLACE(CONVERT(varchar(20), (CAST(NumberCol AS money)/10), 1), '.', ''),4)
           end
    ) ca (NumberStr)

+---+-----------+
|   | NumberStr |
+---+-----------+
| 1 |      0090 |
| 2 |      1481 |
| 3 |      0790 |
| 4 |      0127 |
+---+-----------+

Open in new window

If the value is 17.8, how do you want to display it? 1780 or 0178?
what if it is 17.825?
Avatar of Jeff Jones
Jeff Jones

ASKER

Thanks, Paul... that's close, but not quite right.  

Sharath, here's the issue... it depends.  This is to create a barcode string for a device that uses the values as target ranges for performing tests.  There may be 10 different parameters and depending on the parameter there's an "implied precision".  

For instance,

Param1 = x.xxx
Param2 = xx.xp (where p is a placeholder (i.e., if there's not a digit in replace with a 0)
Param3 = px.xx

I need to be able to format the values (without the decimal point) to match those formats.  However, Param2, for instance, could be 78.5, 78.45, 9.2, 0.8 (the conversions should look like this, respectively, 7850, 7845, 0920, 0008)
ASKER CERTIFIED SOLUTION
Avatar of Sharath S
Sharath S
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial