set the decimal precision for output

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
pyandrea
Posts: 11
Joined: Sun Jul 13, 2014 7:01 pm

set the decimal precision for output

Post by pyandrea »

I would like to set the decimal precision to be used to format floating-point values on output operations (similarly to cout<<setprecision(precision)).
In practical terms, I am developing an endless runner game (similar to Canabalt, Temple Run, Sonic Dash) and the distance from the start of the level is stored as float (e.g. f32 distance_from_start;) but I want to display only 3 decimal values. For instance, I would like to display on screen distance_from_start=127.573451 as "You ran 127.573 meters".

Please, can you suggest me how to do it?
CuteAlien
Admin
Posts: 9734
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Re: set the decimal precision for output

Post by CuteAlien »

You can still use stringstreams like you showed above to build your string. Then pass the result to Irrlicht. So instead of cout you use a variable of type std::stringstream (in <sstream> header). Like:

Code: Select all

 
std::stringstream mystream;
mystream << setprecision(precision);
mystream << myfloat;
irr::stringw irrstring(mystream.c_str());
 
Note that the above also has char* to wchar_t* conversion at the end as Irrlicht usually wants those. You could work with std::wstringstream instead to avoid that, but in my experience that still doesn't work correct on some platforms (for example Android) so I tend to avoid it.
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Post Reply