3

If I have the code:

cv::FileStorage fs("foo.yaml", FileStorage::WRITE);
fs << "myval" << 0.6;

I end up with:

myval: 5.9999999999999998e-01

Of course, I know why floating point isn't exact, but for the sake of neatness in the file I would like to see one of:

myval: 6.00e-01

or:

myval: 0.60

A work-around is:

std::stringstream floatFormat;
floatFormat << std::fixed << std::setprecision(2) << 0.6;
fs << "myval" << floatFormat.str();

But that gives:

myval: "0.60"

Which is of string type.

Is there any way I can force OpenCV to use a specified precision when writing values?

Note, this is a file I consume myself, so I can tweak my reading code to use std::stof() on the fly, but it would nice to have a cleaner solution.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • Have you considered to use some kind of fix point arithmetic instead? In the simplest case, that might be an integral type with a respectively tweaked stream I/O. It's hard to say without knowing what `0.6` represents in your case (i.e. which range with which precision has to be covered). – Scheff's Cat Nov 15 '19 at 07:07
  • @Scheff This number is a scaling factor rather than a money value. – Ken Y-N Nov 15 '19 at 07:50
  • 2
    I did some research and I think it is not possible. I even tried converting your value to a `cv::Mat` and limit the precision with `cv::Formatter`. That works for the `std::cout but` not for the `cv::FileStorage`. I think the best you can do is format to string like you did and read it again as a float. – Grillteller Nov 15 '19 at 09:01
  • 0.6 is double 0.6f is float. May be it will help. – Andrey Smorodov Nov 16 '19 at 12:15

0 Answers0