Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

How to find the decimal places?

royxu
Beginner
1,750 Views
Hello,
I have to ask a dummy question.
X=7.56, I want to get how many decimal places in X. Here it is 2.
What function should I use?
Thanks!
0 Kudos
5 Replies
TimP
Honored Contributor III
1,750 Views
I'm not certain what you mean by this, but it seems unlikely there is a single existing function which would do what you have in mind. If X is a binary floating point value, you could use internal write, probably with G format, to convert it to a character string with the appropriate number of digits (6, including those before the decimal point, for single precision). Then count the non-zero digits after the decimal point.
0 Kudos
Steven_L_Intel1
Employee
1,750 Views
It is important to note that many decimal fractional values cannot be exactly represented in binary floating point. So the approach Tim suggests, which rounds the value to some number of digits, is about the only plausible approach. You have to decide how many extra digits to round to, keeping in mind the fixed precision of the data type (6 or 7 significant digits for single precision, 15 for double.)
0 Kudos
royxu
Beginner
1,750 Views
If you can provide sample codes, that would be very helpful.
I am not 100% sure how to do it.
Thanks!
Roy
0 Kudos
greldak
Beginner
1,750 Views
Ok its not often I use recursion and its not Tims method but anyway
program CountDecPlaces
implicit none
! Variables
integer CountDecimal
! Body of CountDecPlaces
write(*,*)CountDecimal(1.0,0)
write(*,*)CountDecimal(1.234,0)
write(*,*)CountDecimal(1.34,0)
write(*,*)CountDecimal(10.0,0)
write(*,*)CountDecimal(12.1,0)
write(*,*)CountDecimal(1000.0001,0)
end program CountDecPlaces
recursive integer function CountDecimal(Number,Iterations)
integer iterations
realNumber
if (Number .eq. int(number)) then
CountDecimal=Iterations
else
CountDecimal=CountDecimal(Number*10,Iterations+1)
end if
end function
0 Kudos
royxu
Beginner
1,750 Views
I solved it. Thanks!
0 Kudos
Reply