Removing All But The First Two Numbers In A Decimal

19 February 2022 - 1 answer

I'm trying to make a program that converts a number the user inputs into a percentage. Once converted, I want to keep the first two numbers after the decimal, but without rounding off the number. For example, inputting 1.23456 would result in 123.45.

My line of thinking was that I could take the input, separate the string into before and after the decimal place, and from there create a loop that removes the last digits until it has at most 2 decimal places. My issue is that whenever I create something that would have an output greater than 9 for the decimal, I get the error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0, so I can only get decimals to the tenths place at the moment.

My code:

``````import java.util.Scanner;
public class percentage {

public static void main(String[] args) {
try (// TODO Auto-generated method stub
Scanner x = new Scanner(System.in)) {
System.out.println("Please input a number with a decimal to be converted into a percentage: ");
String numberAsString = x.next();
double number = Double.parseDouble(numberAsString);

double percentage = (number * 100);

String toString = Double.toString(percentage);

String[] parts = toString.split("[.]");

String integer = parts[0];
String decimal = parts[1];

int length = decimal.length();

while(length>2) {
decimal = decimal.substring(0,decimal.length()-1);
}
System.out.println("decimal is " + decimal);
System.out.println("integer is " + integer);
}
//System.out.println(decimal);

}
}
``````

``````Double n = input.nextDouble();