Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a trunc function in C++?

Tags:

c++

math

I searched around and couldn't find the trunc function for C++. I know I can do this:

int main()
{
    double a = 12.566789;
    cout << setprecision(2) << fixed << (int)(a * 100) / 100.0 << endl;
    return 0;
}

but I'm not sure it's the best way to do this. Thank you.

like image 568
Alireza Noori Avatar asked Nov 28 '22 12:11

Alireza Noori


2 Answers

If your C library is so old that it lacks a trunc function (specified in C99), you can easily implement one based on floor and ceil (specified in C89)

double trunc(double d){ return (d>0) ? floor(d) : ceil(d) ; }
like image 169
Ken Bloom Avatar answered Dec 11 '22 10:12

Ken Bloom


trunc is there, in <cmath>:

#include <iostream>
#include <cmath>

int main() {
        std::cout << trunc(3.141516) << std::endl; 
}

I suppose you're looking for something else?

like image 27
themel Avatar answered Dec 11 '22 09:12

themel