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 <<
Sure. Use the trunc()
function from math.h. It's a C function, but it works as well in C++ as it does in C. If you want to keep a couple digits, you can always:
double a = 12.566789;
double b = trunc(a * 100) / 100.0;
use ceil
or floor
from cmath
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) ; }
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?
There's a trunc function in C that you can use in C++
trunc(a*100)/100
Keep in mind that you still have to specify formatting requests, because floating point can't represent all real numbers exactly, and you could get output like 12.5600000001
or 12.55999999
if you don't tell the output code the precision you want.
TL;DR
Use the following for output:
cout << setprecision(2) << fixed << a<< endl;
And the following if you need a truncated result somewhere during a mathematical calculation:
trunc(a*100)/100
(Or better yet, use fixed-point math.)
If you're using an ancient C or C++ library that doesn't implement trunc
, use boost::math::trunc.