0

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.

TheWaterProgrammer
  • 4,740
  • 6
  • 35
  • 102
  • Multiply by 10 and assign to an int to truncate it, divide by 10.0f. Be aware that not all floating point numbers can be exactly represented so what you're hoping to do may not always be possible. Since you didn't mention rounding I won't either, but that adds more complexity. It might be better to explain why you need to do this so you can get a complete answer. – Retired Ninja Jul 08 '18 at 22:54
  • Do you understand that `float` values *don't have decimal places*? The concept of "one decimal place" is not meaningful unless you are dealing with a decimal representation of the number. – Daniel Pryden Jul 08 '18 at 23:08
  • 1
    Possible duplicate of [Why can't decimal numbers be represented exactly in binary?](https://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary) – Daniel Pryden Jul 08 '18 at 23:11
  • What do you want to do with the number after it is adjusted? If you want it as a string or as a number in some special decimal format, that is possible. If you want it as a `float`, and your C++ implementation uses a binary-based floating-point, then it is not possible to set `n` to exactly .9, and there are good reasons not to try. If you are trying to do some continued computation after adjusting the number, then add that to your question, and somebody may be able to help. – Eric Postpischil Jul 08 '18 at 23:28
  • 2
    Read this https://floating-point-gui.de – n. 'pronouns' m. Jul 09 '18 at 05:49

1 Answers1

1

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.

Shalom Craimer
  • 18,411
  • 8
  • 66
  • 100