This is the second solution to find the sum of digits from a given float value, by using the String and Character methods.
import java.util.Scanner;
public class SumofdgtsinFloat {
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner inpFloat= new Scanner(System.in);
//Input a float value
System.out.println("Enter a float value=");
float floatNum=inpFloat.nextFloat();
System.out.println("The Float value is="+floatNum);
//Find out the Length
float sumDigits=0, numBackUp= floatNum;
//Convert the two parts of float value into a string
String twoParts=String.valueOf(floatNum);
int lenOfFloat=twoParts.length();
while (lenOfFloat > 0) {
if (Character.isDigit(twoParts.charAt(lenOfFloat-1)))
sumDigits=sumDigits+Character.getNumericValue(twoParts.charAt(lenOfFloat-1));
lenOfFloat=lenOfFloat-1;
}
System.out.println("The sum of digits in a given float value "+numBackUp+" is="+sumDigits);
}
}
Output:
Enter a float value=
21.43
The Float value is=21.43
The sum of digits in a given float value 21.43 is=10.0

Leave a comment