[英]String trim coming out with incorrect length
I am using Java to determine the length of a double as part of a larger program. 我正在使用Java来确定double的长度,作为更大程序的一部分。 At this time the double is 666 but the length is returning as 5, which is a big problem.
此时双倍是666但长度返回为5,这是一个大问题。 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 这打印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. 这也打印5。
Obviously, I want this to print how many digits I have, in this case it should show 3. 显然,我想要打印我有多少位数,在这种情况下它应该显示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.
ie:xx.yyezz其中xx可以是5位数,yy可以是5位数,zz可以是2位数。 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.
所以数字看起来像666.0。 You could see this by printing
String.valueOf(Real)
. 你可以通过打印
String.valueOf(Real)
来看到这一点。 You should use an int
instead or cast the double to an int: 您应该使用
int
代替或将double转换为int:
double Real = 666;
int realInt = (int) Real;
System.out.println(String.valueOf(realInt).length());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.