How to pull out each place of a decimal value

Solved
Super Contributor
Posts: 405

How to pull out each place of a decimal value

I'm trying to get the individual numbers after the decimal place and i'm not sure how to do it.

Say I have .003  I want to pull out the first 0 in d1 and the second to d2 and 3 into d3.

Not sure if the mod function would be the way to go or not.

Thank you

Accepted Solutions
Solution
‎09-13-2011 12:05 PM
PROC Star
Posts: 8,164

Re: How to pull out each place of a decimal value

FriedEgg,  Tom's method correctly deals with negative numbers .. it simply keeps the minus sign.  If the minus sign isn't desired by the OP, a simple solution would be to add an abs function.  e.g.:

data want;

input x;

array digit(3);

do place=1 to 3 ;

digit(place)=abs(mod(int(x*10**place),10));

end;

put;

cards;

.003

.123

12.345

-12.345

;

proc print;

run;

All Replies
PROC Star
Posts: 8,164

How to pull out each place of a decimal value

There may be an easier way, but you can always use brute force. e.g.,

data want;

input x;

d1=int(x*10);

d2=int(x*100-(int(x*10)*10));

d3=int(x*1000-(int(x*100)*10));

cards;

.003

.123

;

Super User
Posts: 8,086

How to pull out each place of a decimal value

This is a math problem. Here is one way using powers of 10, INT and MOD functions.

data _null_;

input x;

put x= @;

do place=1 to 3 ;

digit=mod(int(x*10**place),10);

put digit= @;

end;

put;

cards;

.003

.123

12.345

;

Try it starting from 0 or minus one.

Super Contributor
Posts: 405

How to pull out each place of a decimal value

Tom how can I put the answer in 3 seperate columns for each row?

PROC Star
Posts: 8,164

How to pull out each place of a decimal value

Using Tom's method is the following what you are looking for?

data want;

input x;

array digit(3);

do place=1 to 3 ;

digit(place)=mod(int(x*10**place),10);

end;

put;

cards;

.003

.123

12.345

;

proc print;

run;

Posts: 1,318

How to pull out each place of a decimal value

If you have a negative number this should have one minor flaw.  I cannot test but I believe that if you have say -1.003 then using this method digit3=-3 which you probably do not want. You will probably want to account for this.

Solution
‎09-13-2011 12:05 PM
PROC Star
Posts: 8,164

Re: How to pull out each place of a decimal value

FriedEgg,  Tom's method correctly deals with negative numbers .. it simply keeps the minus sign.  If the minus sign isn't desired by the OP, a simple solution would be to add an abs function.  e.g.:

data want;

input x;

array digit(3);

do place=1 to 3 ;

digit(place)=abs(mod(int(x*10**place),10));

end;

put;

cards;

.003

.123

12.345

-12.345

;

proc print;

run;

Super Contributor
Posts: 405

How to pull out each place of a decimal value

Thank you to everyone for your suggestions.

I used Tom and Art's suggestions.

🔒 This topic is solved and locked.