Round with 2 decimals in C ++

1

In the HUD of my game I show the time ( tipo: float ), but I need it to be mm:ss , that is, 2 decimal places after the comma.

float timeReal = 12.342334;

float timeRedondeado = ...

How can I save it with 2 decimals?

    
asked by Strelok 15.05.2017 в 16:31
source

2 answers

1
  

How can I save it with 2 decimals?

You can not.

Numbers with decimals do not work like this.

Floating-point numbers do not store values up to a certain number of decimals, but save a number expressed in index and exponent stored in binary form.

In C ++ follow the IEEE standard for floating point arithmetic in which each number is represented as follows :

  

r = c × b e

Being:

Thus, the number -12.345 ( r ) could be represented as -12345 ( b ) × 10 -3 ( e ).

Change strategy.

  

In the HUD of my game I show the time ( tipo: float ), but I need it to be mm:ss , that is, 2 decimal places after the comma.

You have a concept problem: the seconds are not decimals of minutes (one minute is not 1/10 of an hour, not 1/60) so you should do time conversions with the different ratio:

  • 0.75 minutes is 45 seconds.
  • 0.5 minutes is 30 seconds.
  • 0.33 minutes is 20 seconds.
  • 0.2 minutes is 12 seconds.
  • 0.1 minutes is 6 seconds.
  • ...

But quiet, you do not need to do any conversion, C ++ has the library <chrono> that allows you to work with units of time:

auto tiempo = std::chrono::system_clock::now();
auto formato = std::chrono::system_clock::to_time_t(now);

std::stringstream ss;
ss << std::put_time(std::localtime(&formato), "%M:%S");

The previous code captures the current time (in the variable tiempo ) and applies the format mm:ss using std::put_time , to get the character string, call stringstream::str .

    
answered by 16.05.2017 / 09:22
source
0

[A] If you want to keep the number, you can use one of the following options:

1) Using the syntax that we use in C, you can do something like the following:

printf("%.2lf", timeReal");

If you want to save the data use sprintf.

2) Another option is the one I show you below with setprecision:

#include <iomanip>

cout << fixed << setprecision(2) << timeReal << endl;

In both cases the rounding will be done to you in the face of the data output. the variable will remain the same.

[B] If you want to operate with rounded quantities, you can use the round () method of the math library.

  • Multiply by 100
  • Round the result with round ()
  • Divide by 100
  • answered by 15.05.2017 в 16:46