Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, scientific notation, format number

Is it possible to format string in scientific notation in the following ways:

  • set fixed places in exponent: 1

  • set fixed decimal places in mantissa: 0

     double number = 123456.789
    

So the number should be formated

  1e+5

I am not able to set 0 decimal points for mantissa:

cout.precision(0);
cout << scientific << number;

result:

1.234568e+005
like image 936
abcdef Avatar asked Aug 20 '11 16:08

abcdef


People also ask

How do you format numbers in scientific notation?

The Scientific format displays a number in exponential notation, replacing part of the number with E+n, in which E (exponent) multiplies the preceding number by 10 to the nth power. For example, a 2-decimal scientific format displays 12345678901 as 1.23E+10, which is 1.23 times 10 to the 10th power.

What is %E in C?

%e. a floating point number in scientific notation.


3 Answers

You can easily do this with the {fmt} formatting library:

#include <fmt/core.h>

double number = 123456.789;
auto s = fmt::format("{:.0e}\n", number); // s == "1e+05"
s.erase(s.size() - 2, 1); // s == "1e+5"

A formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

like image 95
vitaut Avatar answered Sep 22 '22 09:09

vitaut


I can't figure out how to get a single digit in the exponent field but the following matches all your other requirements.

#include <iostream>
#include <iomanip>

int main()
{
  const double number = 123456.789;

  std::cout << std::setprecision(0) << std::scientific << number << std::endl;
}

Output:

1e+05

EDIT:
Did a quick search through the standard (N3291) and couldn't find anything that talked about the number of digits in the exponent field when using scientific notation. This might be implementation defined.

like image 37
Praetorian Avatar answered Sep 18 '22 09:09

Praetorian


You can actualy format anything once you have a string.. more c++ code would look like:

const double number = 123456.789;
const int expSize = 1;
std::ostringstream oss;
std::string output;
oss << std::scientific << number;
unsigned int ePos = oss.str().find("e");
unsigned int dPos = oss.str().find(".");
if(ePos == 0){
    //no exponent
}
else if(dPos == 0){
    //not decimal
}
else{
    output = oss.str().substr(0, dPos) + oss.str().substr(ePos, 2);
    if(oss.str().size()-expSize > ePos+1)
        output += oss.str().substr(oss.str().size()-expSize, oss.str().size());
    else{
        //expSize too big (or bug -> e used but no exponent?)
    }
    std::cout << output;
}

Output:

1e+5

You can set exponent size in expSize and this works for arbitrary large exponent.

Hope it helps!

like image 33
Raven Avatar answered Sep 20 '22 09:09

Raven