Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String trim coming out with incorrect length

Tags:

java

string

I am using Java to determine the length of a double as part of a larger program. At this time the double is 666 but the length is returning as 5, which is a big problem. I read another question posted here with a solution but that didn't work for me. I will show my code and my attempt at emulating the previous solution with results.

My original code:

double Real = 666;
int lengthTest = String.valueOf(Real).trim().length();
System.out.println("Test: " + lengthTest);

This prints 5

Modifications that didn't work, and were essentially just breaking up the code into multiple lines.

    double Real = 666;
    String part = Real + "";
    part = part.trim();
    int newLength = part.length();
    System.out.println("new length : " + newLength);

This prints 5 as well.

Obviously, I want this to print how many digits I have, in this case it should show 3.

For a bigger picture if it helps I am breaking down number input into constituent parts, and making sure none of them exceed limits. ie: xx.yyezz where xx can be 5 digits, yy can be 5 digits and zz can be 2 digits. Thank you.

like image 294
user1814946 Avatar asked Dec 26 '22 17:12

user1814946


1 Answers

That's because you are using a double.

String.valueOf(Real); // returns 666.0, i.e. length 5

Try casting it to an integer first:

Integer simple = (int) Real;
String.valueOf(simple); // returns 666, i.e. length 3.
like image 199
Rogue Avatar answered Dec 28 '22 05:12

Rogue