Display 0.999 as 0.99

How can I display float number = 0.999how 0.99?

1.00Is the print saved in the code below ? I thought using setprecision(2)indicates the number of digits after the decimal point?

#include <iostream>
#include <iomanip>

using namespace std;


int main(int argc, char** argv) 
{     
  const float numberToDisplay = 0.999;
  cout << setprecision(2) << fixed << numberToDisplay << endl;

  return 0;
}  
+3
source share
6 answers

setprecision(2)rounded to the nearest two-digit floating point number, in this case 1.0. If you want to truncate (i.e. Get 0.99), you can always multiply the number by 100 (i.e. 10 ^ [num-digits]), drop it by int and then divide it by float. A bit dirty, but he does his job.

const float numberToDisplay = 0.999;
const float numberTruncated = (int)(numberToDisplay * 100) / 100.0;
// float numberTruncated is 0.99
+13
source

I would use floorf as I feel it expresses your intention better than some other solutions.

cout << setprecision(2) << fixed << floorf(numberToDisplay*100)/100 << endl;
+4

: 0.999 - 1.00.

+2

- , 100 ( 2 ), , "" . , :

#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

int main(int argc, char** argv) 
{
   const double numberToDisplay = 0.999;

   double origInteger;
   double origDecimal;

   modf(numberToDisplay, &origInteger);

   double decimal = numberToDisplay - origInteger;

   //prints .999 even if the number is 12.999
   cout << decimal << endl;

   //results in 99 in origDecimal
   modf(decimal * 100, &origDecimal);
   //integer + .99
   double final = origInteger + (origDecimal / 100);

   cout << final << endl;

   return 0;
}

: casting to (int) , .

0

, , :

:

float const number = value / 1000.0f;
QString string     = QString::number(number, 'f', 3);
string.chop(1);

, :

  • , 3 .

3.

I use the same logic for one million and one gig (10 ^ 9), and I need to change the precision value to 6 and 9, and the chop value should be 4 and 7, respectively.

0
source

Another to throw in there:

#include <cmath>

std::cout << numberToDisplay - std::fmod(numberToDisplay, 0.01f) << std::endl;
0
source

Source: https://habr.com/ru/post/1770432/


All Articles