如何从字符串中获取浮点值

问题描述:

我有一个字符串

> 12.4N-m/kg.

从上面的字符串我需要得到一个值 12.4

From the above string I need to get a value 12.4.

当我使用替换所有函数 str.replaceAll([^。0-9],)

When I use replace all function str.replaceAll("[^.0-9]", "").

当字符串有两个点时,这不起作用。

This doesn't work when then string has two dots.

位置浮点值可能不同。

首先丢弃所有非flot字符,然后转换为Float,如下所示:

First discard all non flot characters and then covert to Float like this:

float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
// now f = 12.4