简体   繁体   English

如何将Float解析为String?

[英]How to parse Float to String exactly?

As the title said: 如标题所说:

I tried: 我试过了:

        Float.toString(float);
        String.valueOf(float);
        Float.toHexString(float);
        float.toString();

But I found if the Float value = 100.00; 但是我发现Float值是否= 100.00; Covert to String value will be 100.0. Covert to String的值将是100.0。 How to avoid it? 如何避免呢? How to be exactly? 究竟如何?

Thanks in advance. 提前致谢。

Edits------------- 编辑-------------

The answers are point to that those which specific the decimal places. 答案指向那些特定于小数位的答案。

确切地说,您最好尝试使用NumberFormat类层次结构将Float格式化为String: http : //docs.oracle.com/javase/6/docs/api/java/text/NumberFormat.html

Its "stupid" to keep 2 zeros at the end. 它的“愚蠢”在结尾保留2个零。 All you've to do is add as many zeros as needed at the moment you're printing it, but internally, it's going to be saved as x.0 您要做的就是在打印它时根据需要添加任意多个零,但是在内部,它将被保存为x.0

Example: 例:

printf ("%.2f", 3.14159);

Prints: 打印:

3.14 3.14

if you are bent upon doing this.. 如果您愿意这样做。

when you get str = "100.0"; 当你得到str =“ 100.0”;

 String[] strNew = str.split(".");

 if(strNew[1].length==1)
 {
 str=str+"0";
 }

BTW A VERY BAD WAY ... 顺便说一下...

float f = 100.00000f;
String expected = String.format("%.6f", f);

The output of this will be : 输出为:

100.000000 100.000000

The length of the numbers after the floating point is done by you. 浮点后的数字长度由您确定。

String.format("%.6f", f) == 100.000000 String.format(“%。6f”,f)== 100.000000

String.format("%.2f", f) == 100.00 String.format(“%。2f”,f)== 100.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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