-1

How to store the returned value of setprecision() ?

For example:-

float fl = /* assign the value returned by setprecision() */ ;

  • 6
    I think you are mistaking here something. What are you trying to achieve with setprecision? I think you want to round up or down your float value? – RoQuOTriX Jun 16 '21 at 06:54
  • 7
    The return type of `std::setprecision` is unspecified. You are only supposed to use it as a stream operator, see https://en.cppreference.com/w/cpp/io/manip/setprecision – Richard Critten Jun 16 '21 at 06:56
  • Are you talking about [std::setprecision](https://en.cppreference.com/w/cpp/io/manip/setprecision) ? If so, the return value should not be used in other way than pushing it to an stream through the `<<` or `>>` operators. – Nicolas Dusart Jun 16 '21 at 06:58
  • It seems you have some major misunderstandings about input in C++. Please [get some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to read and learn properly. – Some programmer dude Jun 16 '21 at 06:59
  • 1
    https://en.cppreference.com/w/cpp/io/ios_base/precision ? – warchantua Jun 16 '21 at 07:14
  • you could try `auto& x = setprecision(n);` but even this may fail and definitely it wont do what you expect. What is your actualy aim? Why do you want to store the returned value? – 463035818_is_not_an_ai Jun 16 '21 at 08:22

2 Answers2

2

I think you're mixing up setprecision(). Let's clear it with an example shall we?

#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
  std::cout << std::fixed;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
  return 0;
}

See the double f? Okay so f has a value of 3.14159. And if we want to control how much places we need to show after the decimal place we'll use setprecision().

Sets the decimal precision to be used to format floating-point values on output operations.

Behaves as if member precision were called with n as argument on the stream on which it is inserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).

This manipulator is declared in header .

and why do you need to use setprecision() for assigning value to a variable?

Hopefully this will give you a clear idea of how to use setprecision()

#include <iostream>  
#include <iomanip> 
using namespace std;
int main()
{
    double var = 10.0 / 3.0 ;
    cout << setprecision(10) << var;

    return 0;
}

result: 3.333333333

1

Let's say you are accepting an input float and you set the precision of the input

std::string s;
std::cin >> std::setprecision(3) >> s;
float f = std::stof(s);

https://en.cppreference.com/w/cpp/string/basic_string/stof

You could also do something similar with other streams