EmiX
EmiX

Reputation: 51

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?

Upvotes: 3

Views: 29832

Answers (2)

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

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.

Upvotes: 10

Jesse Good
Jesse Good

Reputation: 52365

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

Upvotes: 6

Related Questions