Fortran十进制和千位分隔符

时间:2014-08-28 10:40:36

标签: formatting fortran

有没有办法更改逗号的句点小数点分隔符?。

另外,如何使输出数字有千位分隔符?这可能是逗号,句号,空格......

3 个答案:

答案 0 :(得分:4)

您可以编写一个C ++函数,它将为您转换当前语言环境中字符串中的数字。

#include <string>
#include <iomanip> 
#include <sstream>

class SpaceSeparator: public std::numpunct<char>
{
public:
    SpaceSeparator(std::size_t refs): std::numpunct<char>(refs) {}
protected:
    char do_thousands_sep() const { return ' '; }
    char do_decimal_point() const { return ','; }
    std::string do_grouping() const { return "\03"; }
};

extern "C" {

void convert(char* str, double f, int len) {
  std::string s;
  std::stringstream out;
  SpaceSeparator facet(1); //1 - don't delete when done
  std::locale prev = out.imbue(std::locale(std::locale(), &facet));
  out << std::setprecision(15) << f;

  s = out.str();
  std::copy(s.begin(), s.end(), str);
  int i;
  for (i=s.size();i<len;i++){
    str[i] = ' ';
  }
}

}
来自Fortran的电话:

  use iso_c_binding

  interface
    subroutine convert(str, f, l) bind(C,name="convert")
      import
      character(c_char) :: str(*)
      real(c_double), value :: f
      integer(c_int), value :: l
    end subroutine
  end interface

  character(len=100,kind=c_char) :: ch

  call convert(ch, 123456.123_c_double, len(ch, kind=c_int))
  print *,ch
end

在我的机器上打印123 456,123

> gfortran locale.cc locale.f90 -lstdc++
> ./a.out 
 123 456,123                                

免责声明:我不是C ++程序员,他的解决方案可能很慢。也许Fortran中的蛮力方法更好。

我将此答案用作基础:https://stackoverflow.com/a/2648663/721644

答案 1 :(得分:3)

打开文件时使用Argument DECIMAL ='COMMA'

open(100,file=logfile,status='unknown',DECIMAL='COMMA')

这会将小数更改为逗号

答案 2 :(得分:2)

快速而肮脏的基于fortran的方法:

  implicit none

  write(*,*) commadelim(123456.789)
  write(*,*) commadelim(23456.789)
  write(*,*) commadelim(3456.789)
  write(*,*) commadelim(-123456.789)
  write(*,*) commadelim(-23456.789)
  write(*,*) commadelim(-3456.789)

  contains

    function commadelim(v)
      implicit none

      real v
      integer dp,p,z0,i
      character(len=50) :: commadelim

      write(commadelim,'(f0.12)') abs(v)      
      dp = index(commadelim,'.')
      commadelim(dp:dp) = ','
      z0 = 2 - mod(dp+1,3)

      do i = 1, (dp+z0-1)/3-1
        p = 4*i-z0
        commadelim = commadelim(:p)//'.'//commadelim(p+1:)
      enddo

      if (v<0) commadelim = '-'//commadelim
    end function
  end