java:将浮点数转换为字符串,将字符串转换为浮点数 [英] java : convert float to String and String to float

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

问题描述

如何将浮点数转换为字符串或将字符串转换为浮点数?

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;

我尝试了从浮点到字符串:

I tried from float to string:

String sSelectivityRate = String.valueOf(valueCalculated );

但断言失败

推荐答案

使用 Java 的 Float 类.

Using Java’s Float class.

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

要进行比较,最好将字符串转换为浮点数并作为两个浮点数进行比较.这是因为对于一个浮点数,有多个字符串表示形式,当作为字符串进行比较时它们是不同的(例如 "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:将浮点数转换为字符串,将字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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