Convert scientific notation to decimal in C++
Asked Answered
O

3

7

I want to be able to output in decimal and not scientific for all cases in my code.

If I have 122041e+08 then I want it to display as 122041000

If I have 4.6342571e+06 then I want it to display as 4634257.1

... and so on.

Using my code, the output for 4.6342571e+06 is 4634257.100000

void conversion(double counts)
{
  std::ostringstream ss;
  ss << std::fixed << counts;
  std::cout << ss.str() << " MeV";
}

Can someone explain to me why it adds 0's to the end and if it's possible to remove them.

Ozmo answered 23/2, 2012 at 10:24 Comment(0)
G
2

There is a method in your output string stream called precision. You can use it to adjust the number of digits after the comma. It defaults to 6 and missing digits are filled up with 0s (hence the name fixed). In order to achieve 4634257.1 being displayed, set precision to 1:

void conversion(double counts)
{
  std::ostringstream ss;
  ss.precision(1);
  ss << std::fixed << counts;
  std::cout << ss.str() << " MeV";
}
Grandmother answered 23/2, 2012 at 10:37 Comment(0)
L
6

You can use std::setprecision.

Lumumba answered 23/2, 2012 at 10:26 Comment(1)
ideone.com/5CmObK see here scientific number is converting into normal float number by use of std::fixed rather than std::setprecision. I don't claim mine is right but I am telling you what I observing. I am new to c++;Frequentation
G
2

There is a method in your output string stream called precision. You can use it to adjust the number of digits after the comma. It defaults to 6 and missing digits are filled up with 0s (hence the name fixed). In order to achieve 4634257.1 being displayed, set precision to 1:

void conversion(double counts)
{
  std::ostringstream ss;
  ss.precision(1);
  ss << std::fixed << counts;
  std::cout << ss.str() << " MeV";
}
Grandmother answered 23/2, 2012 at 10:37 Comment(0)
B
0

It adds the zeros because you've (unknowingly) asked for them. The default precision is 6, and in fixed format, that means 6 digits after the decimal (regardless of how many before). The precision has a different meaning according to the format being used for the output. (Which doesn't sound very orthogonal, but works out well in practice, once you know what to expect.)

Balk answered 23/2, 2012 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.