Constructing a Float from Integers
QUESTION: I have a integer array of two columns of numbers. I would like to make a floating number, using the integer value of the first column as the integer part of the number and the integer value of the second column as the decimal part of the number. For example:
[345, 678] -> 345.678
How can I do this in IDL?
![]()
ANSWER: The answer to this question came from a variety of sources.
Before I begin with some of the explanations, it is helpful to know a handy algorithm for getting the number of digits in an integer. Apparently, this can be done by recalling your 7th grade math class and the discussion on logarithms. (If your math class occurred more than 40 years ago, you will not need an excuse from the teacher for not remembering this.) The number of digits in an integer can be found by taking the integer part of the base 10 logarithm of the number and adding 1 to it:
IDL> int = 45932L
IDL> numDigits = Long(ALOG10(int)) + 1
IDL> Print, numDigits
5
So, Mike Galloy's solution takes advantage of this fact. He solves the problem like this.
IDL> d = Long(1000 * RandomU(-3L, 2, 5))
IDL> Print, d
897 558
766 589
60 973
37 218
142 984
IDL> num = d[0,*] + d[1,*] / (10.0^(Long(ALOG10(d[1,*])) + 1))
IDL> Print, num
897.558
766.589
60.9730
37.2180
142.984
Bob Stockwell offers a slight variation to this method.
IDL> num = d[0,*] + Float(d[1,*]) / 10^StrLen(StrTrim(d[1,*],2))
IDL> Print, num
897.558
766.589
60.9730
37.2180
142.984
Jean Hasban offers this solution.
IDL> num = d[0,*] + Float('0.' + StrTrim(d[1,*],2))
IDL> Print, num
897.558
766.589
60.9730
37.2180
142.984
![]()
Version of IDL used to prepare this article: IDL 7.0.3.
![]()
Copyright © 2008 David W. Fanning
Last Updated 16 July 2008