• 11
• 9
• 12
• 9
• 11

# 1 decimal point floats

This topic is 2623 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I want to keep my floats as 1 1.2 1.4 1.6 1.8 however somtimes i get things like 1.79999999.
This data will be output to the user and must stay to 1 decimal place.

Best way to do this?

I was thinking *10 then static cast int then /10. that doesnt work though.

##### Share on other sites
if you want to do it that way, you'd do it like so.

float i = 1.78;
i * 10;
i = static_cast<float>( static_cast<int>(i) / 10);

I didn't test it but that should work... that or stringstream can take the float and I believe you can set the width or decimal precision.

something like

std::Stringstream ss;
ss << std::decprec(1) << i;
ss >> i;

I cant remember of the top of my head.

##### Share on other sites
Assuming you are using C++, it might be better to set the precision of the output formatting instead of modifying the number in memory. Streams have a setprecision manipulator you can use. Otherwise, something like double d = (int)(num * 10 + 0.5) / 10.0; should do what you want. You may have missed dividing back by a double instead of an integer.

##### Share on other sites
I think your idea of storing the number * 10 should work, but you may need to use round() instead of the cast?

##### Share on other sites
Considering that most numbers divided by ten cannot be exactly represented by a floating point, the (x*10)/10 is not a great idea (this is probably what is causing your problem). You should use the output formatting options in whatever language you are using instead.

##### Share on other sites
Is it possible for you to just use fixed-point instead of floating-point?

##### Share on other sites
I am using C++.

However I am not using string stream.

This is for the inventory system in my game.
I draw the amount of that item that they have to a texture then draw that.
So any rounding has to be done by me.

Also it needs 1 decimal place to make my math correct and if statements work.

##### Share on other sites
In that case you probably do want to switch to a fixed-point representation as Hodgman suggested. Essentially, you use an integer and always know that it really represents 10 times what the actual value is. There is an implementation of a fixed point number here, but you may be able to find better with a little searching.

##### Share on other sites
If you're using C-style format specifiers, you could use something like this to show only one digit after the decimal point: "%.1f"

Fixed-point representation is a good idea if your internal representation need to be precise, though output does get a little more complicated--especially if you have negative numbers.

When you output the value, you could do something like this, if you've having trouble with any other methods:cout << (value/10) << "." << (value%10) << endl;