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?
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?
How can I save it with 2 decimals?
You can not.
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 ).
In the HUD of my game I show the time (
tipo: float
), but I need it to bemm: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:
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
.
[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.