How could it be done to approximate a number by default and by excess? Understanding that we say, we have the number 2.534823
A default approximation to 4 decimal places would be 2.5348
and for approximation by excess to 4 decimal places, it would be 2.5349
It's like rounding but for a specific decimal place, is there a way to do it in C++?
I have the following example, but it would only be to round to the nearest whole number, whether greater or less:
#include<iostream>
#include<math.h>
using namespace std;
int main(){
float num;
int decim;
cout<<"\tCalcular aproximaciones por defecto y exceso"<<endl<<endl;
cout<<"Ingrese un numero: " ;
cin>>num;
cout<<"Ingresa la cantidad de dedcimales a dejar: ";
cin>>decim;
/*
con ceil y floor me acerca al entero,
ceil al entero más cercano mayor
floor al entero más cercano menor
*/
cout<<"Aproximación por exceso: "<<ceil(num)<<endl;
cout<<"Aproximación por defecto: "<<floor(num)<<endl;
/*
la aproximación debería quedar como:
numero ingresado = 1.432986
para por defecto con 4 decimales, quedaria 1.4329
para exceso con 4 decimales quedaría 1.4323
pero con ceil, subiría a 2
y con floor bajaría a 1
*/
return 0;
}
In C you could truncate a number, to a specified number of decimal places when printing it (i.e. the default approximation):
printf("%.3f", x);
EITHER
printf("%3f", x);
I don't remember which of the 2 ways, what I want to know is how the same could be done but in C++ and also obtain the approximation by excess
As we already know , floating point numbers are imprecise , so doing it directly with the binary value can lead to ... curious results .
A possible solution is to perform the approximation on the value already converted to a string , although this requires us to perform certain operations by hand :
I have not tested it thoroughly ; for test values (
3.1415f
and9.9999f
) displays the following:Note: it is relatively easy to convert it to
template< >
, and, for that matter, add an extra argument to it to be able to use other separators, apart from the period (.
).Use
std::setprecision
, your number with 3 decimal places would be2.535
and with 4 decimal places it would be2.5348
, this code:Produces the following output:
You can see it working on Wandbox . Additionally, you can set the rounding style of floating point numbers using
std::fesetround
, having four rounding styles :FE_DOWNWARD
: Round towards negative.FE_TONEAREST
: Rounding to the nearest representable value.FE_TOWARDZERO
: Round towards zero.FE_UPWARD
: Round towards positive.With rounding down, the above program:
It shows the following output: