简体   繁体   中英

Removing some digits after decimal point in C++

I need to remove digits after decimal points but not all.

For Example, double dig=3.1459038585 i need to convert it to dig=3.14

I think i need to multiple dig to 100 then convert it to integer and then again convert to double and delete to 100 (All this will be 1 line). But is there any function to do this faster?

Any function that implements this functionality will be more flexible, and as such slower by definition. So yes, just write this:

double truncated = (double)((int)dig*100)/100;

It's all CPU-native operations any way so it'll barely cost any clock cycles, especially if inlined or used as a macro.

#include <cmath>
#include <iostream>
int main()
{
    double d = 3.1459038585;
    std::cout << std::floor(d * 100.) / 100. << std::endl; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM