3

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?

EmiX
  • 51
  • 1
  • 1
  • 8
  • 1
    See http://stackoverflow.com/questions/4030190/rounding-to-the-second-decimal-spot – devnull May 22 '13 at 12:23
  • its for printing, i wanted to write PS for such answers. I need to remove digits and use new digits in calculations. – EmiX May 22 '13 at 12:25
  • @devnull that question is about formatting output, not about internal processing. – Niels Keurentjes May 22 '13 at 12:25
  • @NielsKeurentjes Doesn't it list both options -- round & truncate to a given number of decimal places? http://stackoverflow.com/a/4030321/2235132 – devnull May 22 '13 at 12:27

2 Answers2

10

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.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • 6
    Correct but one small typo. It should be (double)((int)(dig*100))/100 - note the parentheses after (int). Otherwise dig is converted (truncated) before it is multiplied – Corvin Jun 27 '16 at 05:53
6
#include <cmath>
#include <iostream>
int main()
{
    double d = 3.1459038585;
    std::cout << std::floor(d * 100.) / 100. << std::endl; 
}
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • 1
    This is actually incorrect since it won't deal with negatives properly. It will return -3.15 if you flip the sign on your d. Niels's version is (almost) correct – Corvin Jun 27 '16 at 05:52
  • 1
    @Corvin: That is a common misconception. [There are many different types of rounding](https://en.wikipedia.org/wiki/Rounding#Tie-breaking). The above way is just showing one style of rounding, which may or may not fit your use case. – Jesse Good Jun 27 '16 at 08:04