以运行时可选的精度打印浮点数 [英] printing a float with runtime-selectable precision

查看:92
本文介绍了以运行时可选的精度打印浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于此问题,但不完全相同.

This is similar to this question but not exactly the same.

我天真地尝试过:

let s prec = "%." ^ (string_of_int prec) ^ "f" in
Printf.printf (s 2) 1.23

,但是这被拒绝,以及将^替换为^^.有什么办法吗?

but this is rejected, as well as replacing ^ by ^^. is there any way to do this?

推荐答案

由于格式字符串是类型安全的,因此应在编译时知道它们.您不能将任意字符串用作格式字符串.这种限制仍然允许您从片段中构建格式,只是不要忘记调用format_of_string函数,并确保所有格式都是静态的,并且生成的格式具有相同的类型.

Since format string are type-safe they should be known at compile time. You can't take an arbitrary string and use it as a format string. This restriction still allows you to build formats from pieces, you just shouldn't forget to call format_of_string function, and make sure that all your formats are static, and resulting formats has the same type.

但是,您的特殊情况已经通过格式解决了,因此您无需在此处做任何花哨的事情.有*说明符,它可以完全满足您的要求:

But, your particular case is already addressed by the formats, so you don't need to do anything fancy here. There is * specifier, that does exactly what you want:

# printf "%.*f" 10 1.0;;
1.0000000000- : unit = ()
# printf "%.*f" 1 1.0;;
1.0- : unit = ()

还有Scanf.format_from_string,它允许您从动态字符串构建任意格式.以下程序演示了OCaml中格式的灵活性:

There is also Scanf.format_from_string that allows you to build arbitrary formats from dynamic strings. The following program demonstrates the flexibility of formats in OCaml:

let () = 
  print_endline "Floating point format: ";
  let f = match read_line () with
    | "engineering" -> "%e"
    | "regular" -> "%f"
    | "pretty" -> "%g"
    | user -> user in
  let fmt =
    try Scanf.format_from_string f "%f" 
    with exn -> invalid_arg "Unrecognized format" in
  Printf.printf (fmt^^"\n") (4. *. atan 1.)

示例:

ivg$ ocaml formats.ml 
Floating point format: 
pi = %.16f    
pi = 3.1415926535897931

这篇关于以运行时可选的精度打印浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆