Reputation: 43
Self studying coding (noob here), the answer to a practice problem is as follows:
amount = (int) round (c);
Where c
is a float.
Is it safe to say that this line converts the float to an integer through rounding?
I tried researching methods of converting floats to integers but none used the syntax as above.
Upvotes: 3
Views: 14092
Reputation: 1290
You should look at the return value of round
.
If it returns a float, then your int
casting will not lose precision and will convert the float to an int
.
If it returns an int
, then the conversion happens in the function, and there is no need to try converting it again.
This is of course if you really wish to round the number. If you want 10.8
to become 11
, then your code is a possible solution, but if you want it to become 10
, then just convert (cast) it to an int
.
Upvotes: 4
Reputation: 5232
float has the higher range than integer primitive value, which means a float is a bigger than int. Due to this fact you can convert a float to an int by just down-casting it
int value = (int) 9.99f; // Will return 9
Just note, that this typecasting will truncate everything after the decimal point , it won't perform any rounding or flooring operation on the value.
As you see from above example if you have float of 9.999, (down) casting to an integer will return 9 . However If you need rounding then use Math.round()
method, which converts float to its nearest integer by adding +0.5 to it's value and then truncating it.
Java tutorial , primitive datatypes
Java language specifications, casting of primitive types
Upvotes: 0
Reputation: 1972
I would just do amount = int(c)
Here is a full example
amount = 10.3495829
amount = int(amount)
print(amount)
It should print 10!
Upvotes: 0