java:将float转换为String,将String转换为float [英] java : convert float to String and String to float

查看:161
本文介绍了java:将float转换为String,将String转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

我尝试从float到string:

I tried from float to string:

String sSelectivityRate = String.valueOf(valueCalculated );

但断言失败

推荐答案

使用Java的 Float class。

Using Java’s Float class.

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

比较它总是更好的将字符串转换为float并比较为两个浮点数。这是因为对于一个浮点数,有多个字符串表示,当作为字符串进行比较时是不同的(例如25!=25.0!=25.00等)。

To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)

这篇关于java:将float转换为String,将String转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆