How to pad Fortran floating point output with leading zeros?

前端 未结 5 1116
执念已碎
执念已碎 2020-12-10 15:57

I have some floating point numbers that I need to output from a Fortran program. Let\'s say the maximum number could be 999.9999 and they are all non-negative. I need zero

5条回答
  •  醉话见心
    2020-12-10 16:30

    This is a trick I used to use in MS BASIC on the Commodore PETs in the late 70s. The code has been modified for negative numbers. If you would like positive numbers to have a leading +, just change the last character of signchr to '+'

    subroutine leadingzero(x)
       real x
       character(len=16) str
       character, dimension(3):: signchr = (/'-', ' ', ' ' /)
       write(str,'(F9.4)') 1000.0 + abs(x)
       write(*,*) signchr(int(sign(1.0,x)) + 2), str(2:) ! drop the 1
    end subroutine leadingzero
    
    program main
       call leadingzero(0.01)
       call leadingzero(0.1)
       call leadingzero(2.532)
       call leadingzero(9.9999)
       call leadingzero(9.999999)
       call leadingzero(10.987)
       call leadingzero(123.456)
       call leadingzero(0.0)
       call leadingzero(-0.01)
       call leadingzero(-0.1)
       call leadingzero(-2.532)
       call leadingzero(-9.9999)
       call leadingzero(-9.999999)
       call leadingzero(-10.987)
       call leadingzero(-123.456)
    end program
    

    Edit - returning result in a string

    subroutine leadingzerostr(x, str_temp)
        real x
        character(*) str_temp
        character(len=10) str
        character, dimension(3):: signchr = (/'-', ' ', ' ' /)
        write(str,'(F10.4)') 10000.0 + abs(x)
        str_temp = str
        str_temp(1:1) = signchr(int(sign(1.0,x)) + 2)
    end subroutine leadingzerostr
    

提交回复
热议问题