0

With a function, I'm getting these values.. 0.07, 0.038, 0.072, 0.078. Now, I'm trying to apply round of to these values so that they should return like this. round(val, decimal_place). So that, 0.038 value should return as 0 and rest should come as 0.1. (I can do it using an if condition like limiting with <0.5>. But, want to know. Is there any such function is there in C++ which limit decimal places below 0.5. It's there in VB by doing like this I think. roundof(value, decimal_place).

wovano
  • 4,543
  • 5
  • 22
  • 49
Zynk
  • 33
  • 5
  • Does this help? https://stackoverflow.com/questions/14369673/round-double-to-3-points-decimal – paddy Nov 03 '22 at 02:20
  • It is only possible on output (e.g. output a value to three decimal places or to three significant figures). A floating point variable cannot represent all multiples or powers of `0.1` precisely. The reason is that floating point variables (with a base-2 aka binary mantissa) can only represent fractional values that are the sum of negative powers of 2. So `0.1` or `0.3` (decimal) cannot be exactly represented, but `0.5` and `0.25` (which are negative powers of 2) and `0.75` (which is a finite sum of negative powers of 2) can be. – Peter Nov 03 '22 at 02:38

1 Answers1

1

You can use setprecision() to limit the decimal place on floating point numbers.

var = 1.0 / 3.0; // returns 0.33333333...

cout << fixed << setprecision(1) << var; // returns 0.3
Askarr
  • 21
  • 2