How to limit decimal places?

Asked

Viewed 57,301 times

10

I have a question, it has to limit the number of decimal places in C++?

float x = 2.958;

Instead of rounding up or down using floorf, roundf, can only take the two numbers after the comma?

that would look something like this

float x = 2.95;
  • You can limit when printing, that’s it ?

2 answers

9


  • 1

    Show on the screen I can even, the problem is when you pass this value to a variable.

  • With float you cannot limit the amount of decimals. You can even try rounding, but this doesn’t work because of the way it’s stored. It is binary and not decimal, so it can always an unexpected value and undefined number of houses. You can only control the number of houses in the presentation. If you need to control the number of decimal places in the value, you cannot use float.

  • 1

    understood, another type of variable could work double type?

  • No, the double has the same problem, has to use a decimal type or create a mechanism of its own. http://answall.com/a/38140/101

5

You can achieve the expected value using the function floorf(), thus:

#include <iostream>
#include <cmath>
using namespace std;


int main(){
    float x = 2.958;
    cout << floorf(x * 100) / 100;
    return 0;
}

See working on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.