How to convert an int to scientific notation in C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <cmath>

std::string toScientificManual(int n) {
    if (n == 0) return "0e+0";

    int exponent = 0;
    double mantissa = n;

    while (std::abs(mantissa) >= 10.0) {
        mantissa /= 10.0;
        exponent++;
    }
    while (std::abs(mantissa) < 1.0) {
        mantissa *= 10.0;
        exponent--;
    }

    char buffer[64];
    std::sprintf(buffer, "%.6fe%+d", mantissa, exponent);
    return buffer;
}


int main() {
    int x = 123456789;

    std::cout << toScientificManual(x);
}


/*
run:

1.234568e+8

*/

 



answered Feb 25 by avibootz
0 votes
#include <iostream>
#include <iomanip>

int main() {
    int x = 1234567891;

    std::cout << std::scientific << static_cast<double>(x) << "\n";
    
    std::cout << std::scientific << std::setprecision(3)
              << static_cast<double>(x) << "\n";
}



/*
run:

1.234568e+09
1.235e+09

*/

 



answered Feb 25 by avibootz

Related questions

1 answer 130 views
1 answer 156 views
2 answers 240 views
1 answer 192 views
1 answer 210 views
...