Detecting whether there are any format flags

So, I have a type where I would like to make "{:.6}" (or really, any non-empty set of formatting flags) to apply the flags to all floats.

(this is for the benefit of researchers using the code, who may prefer to have cleaner, more readable files)

println!("{:.6}", poscar);

  2.300000 0.000000 0.000000
  5.654300 7.777777 0.000000
  0.000000 0.000000 30.000000

But I want it to default to dtoa whenever no flags are given, for its immense superiority to the default formatter.

(this is my personal use case, which prioritizes round-trip precision for conveyance of data between separate programs, but which also keeps readability as a secondary priority for the times when an intermediate file must be inspected by a human)

println!("{}", poscar);

  2.3 0.0 1.346658231798743e-8
  5.6543 7.777777777774996 0.0
  0.0 0.0 30.0

Can anyone think of what might be the best way to do this? Seprately checking a ton of fmt::Formatter properties sounds wasteful, and like a possible back-compat hazard.

Alternatively, do you know of any notable problems with a design like this that should give me pause? Or better ways to provide an API that serves both use cases?

If you're just wanting to know if any formatter flags were provided, could you use the (deprecated) Formatter::flags() method?

Calling Display::fmt directly on the child floats will cause their formatting to inherit all options passed into your display call. If you're currently doing something like write!(f, "{}", some_float)?;, doing some_float.fmt(f)? instead should work.

This doesn't help if you want to somehow store these options, or if you want more fine-grained control - but if your goal is simply to allow formatting all internal floats using external formatting flags, it should function well enough.

Thank you, though I am indeed aware of how to forward formatting args. As I said, I am currently not using "{}" or anything like that, I am using the dtoa crate. Thus, I require separate code paths for with flags (i.e. use Display::fmt) versus without flags (i.e. use dtoa).

I want dtoa for the default case, because, for instance, one notable problem that can be encountered in my field is having a very small, negative value, such as -1e-30. (such a value has the property that (-1e-30).mod_floor(1.0) evaluates to 1.0 rather than 0.0) I don't want these values to be printed like -0.000000000000000000000000001241645781555 and force me to play a counting game.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.