Question

I am trying to find the scientific notation with double and i could not find any function or way to do this.

My variable is double and I need to get the scientific notation from it, for example:

3.44828e+026

I need to somehow get the number 026 from my double variable.

By the way, the number is actually 28 long and not 26, is there a way to fix that too? (not adding 2 to the result)

Thanks in advance!

Was it helpful?

Solution

This should work if y is non-negative. For negative y, the result if off-by-one. Fix it yourself if needed.

#include <iostream>
#include <cmath>

int main()
{
    double x = 3.44828e+026;
    int y = (int)log10(x);
    std::cout << y << std::endl;  
    return 0;
}

Output: 26

OTHER TIPS

Answer similar to Yu Hao's but this one seems to work for negative exponents as well (but I haven't fully tested it):

#include <iostream>
#include <cmath>

// pre-condition: x != 0.0
int exponent(double x) {
    double y = log10(x);
    if (y < 0.0)
        y -= 1.0;
    return static_cast<int>(y);

}

int main() {
    std::cout << exponent(3.44828e+026) << '\n';
    std::cout << exponent(3.44828e-026) << '\n';
}

Outputs 26 and -26.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top