Does C++ type conversion do rounding automatically?

40 Views Asked by At

I have the following code:

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

int main(){
    uint64_t value = uint64_t(1693829987930866899) / 1000.0;
    std::string str_value = std::to_string(value);
    printf("value=%lu, str_value=%s len=%lu\n", value, str_value.c_str(), str_value.size());
}

Output:

value=1693829987930867, str_value=1693829987930867 len=16

The expected output is 1693829987930866 but I got 1693829987930867. Does the g++ compiler do rounding automaticlly?

1

There are 1 best solutions below

0
xaxxon On

See the warnings here: https://godbolt.org/z/vzE3976hP -- it says what @n.m.couldbeanAI says -- it's converting to double because you wrote 1000.0 not just 1000


The following link/code does what you want it to (note the additional cast -- or just type 1000 not 1000.0 in your original code)

https://godbolt.org/z/66Wxj6vvj

#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstdint>
using namespace std;

int main(){
    uint64_t value = uint64_t(1693829987930866899) / uint64_t(1000.0);
    std::string str_value = std::to_string(value);
    printf("value=%lu, str_value=%s len=%lu\n", value, str_value.c_str(), str_value.size());
}

value=1693829987930866, str_value=1693829987930866 len=16