Riya
Riya

Reputation: 71

Long to Float Conversion in Android

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

Answers (2)

omikes
omikes

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

O.O.Balance
O.O.Balance

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

Related Questions