TheWaterProgrammer
TheWaterProgrammer

Reputation: 8259

How to reduce floating point number decimal places without doing couts on it

I have a floating point number

float n = 0.948245;

I want to reduce this number to 1 decimal place that should be 0.9. I dont want to std::cout or log this number anywhere. Just want make set the value of n to 0.9.

How can I do this with C++ 14 ?

PS: Of all the suggestions I found, all of them somehow involve std::couting the float. Hence, stated it out that I dont want o cout it.

Upvotes: 0

Views: 188

Answers (1)

Shalom Craimer
Shalom Craimer

Reputation: 21459

This is what std::round() and std::trunc() are for. std::trunc() finds the nearest integer that is not greater than the input. Since you want just 1 decimal place, multiply by 10 (just like @Retired Ninja wrote) before passing it to the function:

float n = 0.948245;
float result = std::trunc(n*10) / 10.0f;

That being said, I'd caution you that float is not very precise. See the following example in wandbox:

float n = 100000.948245;
std::cout << n << "\n";

The output is:

100001

The problem is that the number assigned here to n is both large and also has a lot of digits after the decimal place. (BTW, "large" for float means anything far from the 0 to 1 range).

Using double is a little better, but if you really care about precision even in large numbers, you'd be better off using fix-point math. You really have to take into account the ranges of values you care about.

Upvotes: 1

Related Questions