0
votes

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!

2
You're looking for the logarithm... - Kerrek SB
If the wrong exponent is displaying, you must be dividing the number by 100 before printing it. Computers don't usually get simple arithmetic wrong like that. - Barmar
actually I am not dividing by 100. - Naor Hadar
@zakinster 1e+28 - 1 is 1e28 on most machines. (Machine floating point values are not real numbers, and don't obey the rules of real number arithmetic.) - James Kanze
@JamesKanze Good point, but on those machine, 1e+28 == 9.99e+27, anyway that doesn't change the result, 1e+28 / 29 = 3.xx e+26. - zakinster

2 Answers

1
votes

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

1
votes

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.