Reputation: 71
How to covert a Long
value to Float
in Android?
Float
amt=NumberFormat.getNumberInstance(Locale.US).parse(products.get(i).getAmount().substring(0,products.get(i).getAmount().length() - 3));
This code arises the error
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Float
Upvotes: 0
Views: 1734
Reputation: 8513
For simplicity and readability's sake, first get the NumberFormat
, then cast the parsed Number
to a float with floatValue()
.
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
String amount = products.get(i).getAmount();
Number number = numberFormat.parse(amount.substring(0,amount.length() - 3));
Float amt = number.floatValue();
Upvotes: 2
Reputation: 3040
You can call floatValue()
to get a float
representation of your Long
(or any Number
for that matter). Then you can use the constructor Float(float)
to create a Float
object. This has the advantage of not relying on the Number
returned by your code to be a Long
.
Number amt = NumberFormat.getNumberInstance(Locale.US).parse(products.get(i).getAmount().substring(0,products.get(i).getAmount().length() - 3));
Float amtFloat = new Float(amt.floatValue());
Upvotes: 2