Float with one unrounded decimal C ++ [closed]

0

A cordial greeting to all.

I need help, I want a number for example 0.57, to be expressed as 0.5.

that is to say with only one decimal without rounding. I could express with a decimal but it is rounded, for example: 0.57, it is expressed in 0.6.

What code do I have to use?

    
asked by Ariel Pedraza 01.03.2018 в 19:43
source

2 answers

1

You can control the rounding style of floating point numbers with:

In combination with the std::fesetround function, all belonging to the header <cfenv> . Since you need to round down, use that function like this:

auto f = 0.57f;
std::cout << f << '\n'; // Muestra 0.57
std::cout << std::setprecision(1) << f << '\n'; // Muestra 0.6

std::fesetround(FE_DOWNWARD); // Aplicamos el redondeo a la baja
std::cout << std::setprecision(2) << f << '\n'; // Muestra 0.56
std::cout << std::setprecision(1) << f << '\n'; // Muestra 0.5
    
answered by 01.03.2018 в 23:42
0

In C ++ another solution can be

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

using namespace std;

int main()
{
    float num = 0.57;
    cout<<floor(10*num)/10<< endl;

    return 0;
}

Demo

    
answered by 01.03.2018 в 20:08