Limit floating point precision?
Asked Answered
Q

9

16

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

Quadric answered 1/8, 2010 at 21:29 Comment(3)
Do you mean for display or calculation?Leboff
3576.7675745342556 becomes 3576.77, doesn't it?Paleogeography
@Vladimir: Not nesacerily. rounding is a vague term that encapsulates several different operations that have more exact meaning. Round Up/Down/Towards Zero/Towards Infinity/Towards nearest int etc.Groundmass
C
20
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)); 
}
Correlate answered 1/8, 2010 at 21:29 Comment(3)
Note that because binary floating point can't represent most decimal values exactly, this answer won't work when you start examining the lower digits closely. But then again neither can any other answer.Guileless
Why do you use floor instead of round in the more flexible version?Truth
value * pow(10, precision) + 0.5 approach fails 1) many negative values, 2) the addition incurs imprecision in half-way cases, 3) multiplication overflows.Blat
F
15

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

Firebrat answered 1/8, 2010 at 21:54 Comment(5)
Never refer to another answer with "as mentioned above". The order in which answers are displayed varies over time and according to user-configurable preferences (sort by time or number of votes). To address your particular point, floor or ceil can be used instead of an integer cast.Ciscaucasia
@Svante , because we are using C++?Eyler
While cout might be preferred in C++, you can use printf in C or C++. E.g. std::printf("Printf C++\n");Finnish
What I meant is printf("%.2f", f);.Nullifidian
what # include is this?Deceit
C
3

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.

Chianti answered 1/8, 2010 at 21:30 Comment(1)
Decimal fixed-point integers are quite possibly the real right answer here.Merriweather
B
3

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.

Boyhood answered 30/7, 2015 at 19:5 Comment(0)
L
2

Don't use floats. Use integers storing the number of cents and print a decimal point before the last 2 places if you want to print dollars. Floats are almost always wrong for money unless you're doing simplistic calculations (like naive economic mathematical models) where only the magnitude of the numbers really matters and you never subtract nearby numbers.

Locular answered 2/8, 2010 at 5:41 Comment(0)
A
1

try use

std::cout<<std::setprecision(2)<<std::cout<<x;

should works and only 2 digit after the floating point appear.

Abruption answered 24/7, 2015 at 15:12 Comment(0)
R
1

Try this, it works perfectly

float=3576.7675745342556;
printf("%.2f",float);

change some objects in it to see and learn the code.

Resee answered 15/10, 2017 at 4:43 Comment(0)
T
1

I didn't find a clean answer that satisfied me since most of the clean answers assume you need to print the result which might not be the case if you are just storing some data to the acceptable resolution:

#include <sstream>

template<typename T>
T toPrecision(T input, unsigned precision)
{
    static std::stringstream ss;

    T output;
    ss << std::fixed;
    ss.precision(precision);
    ss << input;
    ss >> output;
    ss.clear();

    return output;
}

template<unsigned P, typename T>
T toPrecision(T input) { return toPrecision(input, P); }

// compile-time version
double newValue = toPrecision<2>(5.9832346739); // newValue: 5.98
// run-time version
double newValue = toPrecision(3.1415, 2); // newValue: 3.14

You can also add static checks for T and precision (in the case of the compile-time signature).

Truth answered 6/1, 2021 at 2:35 Comment(3)
Expensive approach yet functionally forms the best answer, even in most, if not all, corner cases.Blat
@chux-ReinstateMonica I have made stringstream static to somewhat reduce cost and removed the confusing comment. CheersTruth
@Truth making the stream static makes your function non thread-safe, likely not to a good idea; at least, you might make it thread_local, if you insist on it not being scope local.Orientation
H
0

To limit the precision:
If x is a float, no rounding:
(shift up by 2 decimal digits, strip the fraction, shift down by 2 decimal digits)

((int)(x*100.0)) / 100.0F

Float w/ rounding:

((int)(x*100.0 + 0.5F)) / 100.0F

Double w/o rounding:

((long int)(x*100.0)) / 100.0

Double w/ rounding:

((long int)(x*100.0 + 0.5)) / 100.0

Note: Because x is either a float or a double, the fractional part will always be there. It is the difference between how a # is represented (IEEE 754) and the #'s precision.
C99 supports round()

Hopeh answered 6/8, 2013 at 16:22 Comment(1)
(int)(x*100.0) fails when the product is out of int range. Even using intmax_t is insufficient. x*100.0 + 0.5F fails like this.Blat

© 2022 - 2024 — McMap. All rights reserved.