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);
}
}
CodePudding user response:
Multiply by 10,000 (100 for percentage, 100 for the two decimal places), truncate to integer, divide by 100 (to get back to percentage).
Writing it out one step at a time, for clarity of exposition:
Double n = input.nextDouble();
int i = (int)(n * 10_000);
Double pc = i / 100.0;
System.out.printf("%.2f\n", pc);
CodePudding user response:
You have the number as a String in the variable toString
. Use regex to trim all characters after the 2nd decimal (if any exist).
It’s a one-liner:
toString = toString.replaceAll("(?<=\\...).*", "");
Or just print it directly:
System.out.println(toString.replaceAll("(?<=\\...).*", ""));