Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit floating point precision?

Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.

like image 661
jmasterx Avatar asked Aug 01 '10 21:08

jmasterx


People also ask

How do you limit float precision?

Using std::ios_base::precision You could use std::ostringstream with the precision specifier as for std::cout . With C, you can achieve the same with the %. 2f format string in the printf() function. That's all about restricting a floating-point value to two places after the decimal point in C++.

Why do floating-point numbers have limited precision?

Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results.

What are the limitations of floating-point representation?

As a result, they do not represent all of the same values, are not binary compatible, and have different associated error rates. Because of a lack of guarantees on the specifics of the underlying floating-point system, no assumptions can be made about either precision or range.


4 Answers

round(x * 100) / 100.0

If you must keep things floats:

roundf(x * 100) / 100.0

Flexible version using standard library functions:

double GetFloatPrecision(double value, double precision)
{
    return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision)); 
}
like image 52
strager Avatar answered Oct 21 '22 16:10

strager


If you are printing it out, instead use whatever print formatting function available to you.

In c++

cout << setprecision(2) << f; 

For rounding to render to GUI, use std::ostringstream

like image 45
carlsborg Avatar answered Oct 21 '22 15:10

carlsborg


Multiply by 100, round to integer (anyway you want), divide by 100. Note that since 1/100 cannot be represented precisely in floating point, consider keeping fixed-precision integers.

like image 3
Tassos Bassoukos Avatar answered Oct 21 '22 14:10

Tassos Bassoukos


For those of you googling to format a float to money like I was:

#include <iomanip>
#include <sstream>
#include <string>

std::string money_format (float val)
{
    std::ostringstream oss;

    oss << std::fixed << std::setfill ('0') << std::setprecision (2) << val;

    return oss.str();
}
// 12.3456 --> "12.35"
// 1.2 --> "1.20"

You must return it as a string. Putting it back into a float will lose the precision.

like image 3
xinthose Avatar answered Oct 21 '22 15:10

xinthose