Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

java - java:将float转换为String,将String转换为float(java : convert float to String and String to float)

How could I convert from float to string or string to float?

(我如何从float转换为string或string转换为float?)

In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.

(在我的情况下,我需要在2个值字符串(我从表中获得的值)和我计算的浮点值之间进行断言。)

String valueFromTable = "25";
Float valueCalculated =25.0;

I tried from float to string:

(我尝试从float到string:)

String sSelectivityRate = String.valueOf(valueCalculated );

but the assertion fails

(但断言失败了)

  ask by lola translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using Java's Float class.

(使用Java的Float类。)

float f = Float.parseFloat("25");
String s = Float.toString(25.0f);

To compare it's always better to convert the string to float and compare as two floats.

(比较它总是更好地将字符串转换为float并比较为两个浮点数。)

This is because for one float number there are multiple string representations, which are different when compared as strings (eg "25" != "25.0" != "25.00" etc.)

(这是因为对于一个浮点数,有多个字符串表示,当作为字符串进行比较时它们是不同的(例如“25”!=“25.0”!=“25.00”等))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...