0

While formatting a float number, I get an unexpected result.
For example writing any of this

float argument = 40.432;
char buff[100];
snprintf(buff, sizeof(buff), "%f", argument);
std::string result = buff;

or

std::string result = boost::str(boost::format("%"  + "f")%argument);

the value of result is 40.431999, while if I set the value of argument 40.111 instead of 40.432 , the result will be 40.111000, as it is accepted. And if I set the value of argument 40.4, the result will be 40.400002.

Now I understand why it is so, and my question is how can I get 40.432000 as a result?

Karine
  • 176
  • 1
  • 11
  • this is float.. – purec May 30 '18 at 17:13
  • 2
    C and C++ take entirely different approaches here. Which one are you looking to use? Is this a C++ question or a C one? – tadman May 30 '18 at 17:14
  • I need a solution for my problem, I am working with c++ , but have thought that may be the solution is C specific. – Karine May 30 '18 at 18:26
  • BTW, always search the internet or StackOverflow before posting. – Thomas Matthews May 30 '18 at 18:41
  • Looks like you are programming in C++ because the C language doesn't have the `std::string` data type. Please update your tags accordingly. – Thomas Matthews May 30 '18 at 18:42
  • How many different `float` are representable in a 32-bit variable? (about 2^32 or about 4,000,000,000) Is `40.432` one of those 4,000,000,000? (No) What is the closest `float` to `40.432` (40.43199920654296875) How does that print with `"%f"` with its default of 6 digits after the `.`? ("40.431999") What is the next closest `float`? (40.432003021240234375) – chux - Reinstate Monica May 30 '18 at 19:17

0 Answers0