2

There are functions to bring out the integer value and also to round up the value. But I want the first decimal value in a new variable. How can I do that. for ex: if the valur is 12.62 I want 0.6 in the new variable. and 12 in another variable.

newvar1 =INT(12.62)   /* this gives 12 as output*/
newvar2 =??(12.62)    /* for the output to be 0.6*/
user3658367
  • 641
  • 1
  • 14
  • 30

5 Answers5

3

You wanted a function - you can roll your own in 9.3+ .

proc fcmp outlib=work.funcs.math;
  function firstdec(in);
    out = floor(in*10 - floor(in)*10)/10;
    return(out);
  endsub;
quit;

options cmplib=work.funcs;

data _null_;
  x=12.62;
  newvar = firstdec(x);
  put newvar=;
run;
Joe
  • 62,789
  • 6
  • 49
  • 67
  • Of course any of the above solutions could also be used inside the `firstdec` function - I used my preferred method. – Joe Jun 05 '15 at 15:00
  • One caveat I realised afterwards is that `floor` only works in this case with positive numbers. If there are negative numbers then `int` is a better option – Longfish Jun 05 '15 at 16:16
2

Use a combination of floor and mod to truncate the decimal rather than round. mod returns the remainder when the first number is divided by the second.

data first_decimal;
input x;
y = int(x);
z = floor(mod(x, int(x))/0.1) * 0.1;
datalines;
12.62
;
run;
Longfish
  • 7,582
  • 13
  • 19
1

Try using the floor function.

yourvar = 12.62;
newvar2 = round(yourvar - floor(yourvar), .1);
Oliver
  • 194
  • 4
  • 10
  • Hi, but this rounds off the 0.62 to 0.6 and 0.68 to 0.7 I am looking to bring out the first decimal value. – user3658367 Jun 05 '15 at 10:15
  • You can't use `round` where the 2nd decimal is between 5 and 9. e.g. 12.65 will show as 0.7 – Longfish Jun 05 '15 at 10:15
  • You are correct keith., I actually used character function and then converted it to numeric after scan function...like this: `code` f=put(a,5.3); `code` r=substr(scan(f,2,'.'),1,1); `code` u=(input(r,best.))/10; This might not be the best way to do it.. so I am windering if we have any numeric function, – user3658367 Jun 05 '15 at 10:16
1

Keith's answer is also correct he is doing mathematical operations, while I am performing char functions

  1. Converting the numeric to character.
  2. Scanning for the decimal "." and obtaining the next character
  3. Appending 0. to the obtained number in 2

data _NULL_;
input x;
y = int(x);
k= cat("0.",substr(scan(put(x,best32.),2,"."),1,1));
datalines;
12.6212
;
run;
in_user
  • 1,948
  • 1
  • 15
  • 22
0
newvar1 =INT(12.62) ; 
newvar2 =abs(12.62) - INT(12.62) ;  /* --> THIS GIVES .62 AS OUTPUT.*/

If you want .6 as output then it is

NEWVAR2 = ROUND((ABS(12.62) - int(12.62)),.1);