Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing all but the first two numbers in a decimal

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
        
    } 
}

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading