user13986339
user13986339

Reputation:

Why java substring not working in this case?

I've written a code where java code selects digit before decimal point in different variable and digits after decimal point in different variable. For example in the below code we have 23.256 Now the code that i have written will select 23 in firstDigit variable and .256 in lastDigit variable. Now problem comes when there is no digits after decimal point for example if we have 23 this will crash.

What I've written is (THIS WORKS)

totalAmount = 23.256;
String totalAmountString = new BigDecimal(String.valueOf(totalAmount )).toString();
String firstDigit= totalAmountString .substring( 0,totalAmountString .indexOf('.'));
String lastDigit= totalAmountString .substring( totalAmountString .indexOf('.'), totalAmountString .length());

It doesn't work

totalAmount = 23;
String totalAmountString = new BigDecimal(String.valueOf(totalAmount )).toString();
String firstDigit= totalAmountString .substring( 0,totalAmountString .indexOf('.'));
String lastDigit= totalAmountString .substring( totalAmountString .indexOf('.'), totalAmountString .length());

totalAmount will be provided by user so we don't know if there will digit after decimal point or not. Problem when user enters the totalAmount without any digit after decimal point the code crashes.

Any help will be appreciated :)

Upvotes: 1

Views: 77

Answers (3)

Basil
Basil

Reputation: 1893

The following code worked for me.

double totalAmount = 23.256;
String totalAmountInString = String.valueOf(totalAmount).toString();
//Checks wether the totalAmount has value after decimal     
if (totalAmount % 1 != 0)
{
     //totalAmount has value after decimal
     String firstDigit = totalAmountInString.substring( 0,totalAmountInString .indexOf('.'));
     String lastDigit= totalAmountInString.substring( totalAmountInString.indexOf('.'), totalAmountInString.length());
     System.out.println("Before Decimal : " + firstDigit);
     System.out.println("After Decimal : " + lastDigit);
}
else
{
     //totalAmount has no value after decimal
     System.out.println(totalAmountInString + " Has no decimal");
}

Good Luck!

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 166

You can use split method of String class

   String totAmountStr = new BigDecimal(String.valueOf(23.256)).toString();
    String[] split = totAmountStr.split("\\.");
    String firstDigit= null;
    String lastDigit= null;;
    if (split.length > 1) {
         firstDigit = split[0];
         lastDigit = split[1];
    } else {
         firstDigit = split[0];
    }

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89517

You need to first check if the index is -1, meaning that no decimal point was found.

int idx = totalAmountString .indexOf('.');
String firstDigit=  idx != -1 ? totalAmountString .substring( 0, idx): totalAmountString;
String lastDigit= idx != -1 ? totalAmountString .substring(idx, getAcreIntoString.length()): "";

Upvotes: 1

Related Questions