float x = 1.33333333333333 why does it equal 1?

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

Recommended Posts

Hi, I have made a float like so float x = 400/300 400/300 = 1.333333333333333333333333333333333 When i find out what value x is like so this.text = x.tostring(); text = 1 for some reason Do recurring numbers get rounded off if so, how can i keep it so x = 1.3333? Thanks for any info

Share on other sites
because you are doing an integer division.

float x = (float)400/300

That will do what you want.

Share on other sites
If both numbers on either side of a division are integers a ‘integer division’ is performed. This is basicly a division that is trunctuated to an integer (for the sake of speed). To solve this you can cast the values as floats or doubles.

Example:

Floats:
400.0f / 300.0f

Floats:
( float ) 400 / (float ) 300

Doubles:
400.0 / 300.0

Hope this helps,
Jackson Allan

Share on other sites
Quote:
 Original post by Xetrovbecause you are doing an integer division.float x = (float)400/300

Casting literals is strange. Why not this?

    float x = 400.0f / 300.0f

Share on other sites
Quote:
 Casting literals is strange. Why not this? float x = 400.0f / 300.0f

Fair enough, but that doesnt exactly work when you want to use variables instead ;)

Share on other sites
Quote:
 Original post by XetrovFair enough, but that doesnt exactly work when you want to use variables instead ;)

(Kicking the man while he's down.)
C casts are evil (unless you're programimng in pure C).
Prefer static_cast<float>(a)/b.
That way it is obvious what the cast is applied to.
(does the cast in (float)a/b apply to a or to a/b ?)

[wink]

Share on other sites
I see :)
Thanks everyone :)

Share on other sites
Quote:
 Original post by FrunyPrefer static_cast(a)/b. That way it is obvious what the cast is applied to.(does the cast in (float)a/b apply to a or to a/b ?)

Although C-casts are ugly, I usually find this nice:
float(a)/b

Share on other sites
That's not a C cast, you're creating a temporary float from a. I guess in the end it's exactly the same, but I'm going to say they're different, so har!

Share on other sites
Quote:
Original post by dalleboy
Quote:
 Original post by FrunyPrefer static_cast(a)/b. That way it is obvious what the cast is applied to.(does the cast in (float)a/b apply to a or to a/b ?)

Although C-casts are ugly, I usually find this nice:
float(a)/b

float x = (float)(a/b) is the way I did

• Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 15
• 22
• 17
• 46