简体   繁体   中英

String trim coming out with incorrect length

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.

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.

A double always puts a decimal place after the number. So the number looks like 666.0. You could see this by printing String.valueOf(Real) . You should use an int instead or cast the double to an int:

double Real = 666;
int realInt = (int) Real;
System.out.println(String.valueOf(realInt).length());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM