csvracket

How do I alter the precision of output from csv-writing in Racket?


I am using display-table from the csv-writing package, and would like to alter the default precision when converting numbers to strings for output. I can see the docs say to use make-csv-printing-params and #:number-cell->string, but it also says it uses the ~r parameter #:precision. I tried to make all this fit together, but not successfully:

(display-table each_rank_table vars_out_port
           #:printing-params
           (make-csv-printing-params
           #:number-cell->string
           (~r #:precision 8)))

I assume I somehow need to get the cell value into ~r (?), so I presume I'm not going about this in the right way.


Solution

  • You have to give it a function that takes a numeric argument and returns a string - one that just calls ~r would be easiest.

    Examples:

    (make-csv-printing-params
      #:number-cell->string (curry ~r #:precision 8))
    

    or

    (make-csv-printing-params
      #:number-cell->string (lambda (n) (~r n #:precision 8)))
    

    Note that if you want trailing 0's in the output, you need to use '(= 8) for the precision:

    > (~r 3.2 #:precision 8)
    "3.2"
    > (~r 3.2 #:precision '(= 8))
    "3.20000000"