How to limit decimals?

6

I have a question, can you limit the number of decimal places in C ++?

float x = 2.958;

Instead of rounding up or down using floorf , roundf , can you just pick up the two numbers after the comma?

That would look more or less like this

float x = 2.95;
    
asked by anonymous 26.10.2015 / 12:27

2 answers

7

One way would look like this:

#include <iostream>
using namespace std;

int main() {
    float num = 3.14159;
    cout << fixed;
    cout.precision(2);
    cout << num << endl;
    printf("%.2f", num); //apenas se for usar em C puro, não use em C++
    return 0;
}

See running on ideone .

    
26.10.2015 / 12:35
2

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

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


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

See working at Ideone

    
26.10.2015 / 13:21