如何在Java中将分数格式的字符串从小数转换为浮点数或浮点数?

问题描述:

我从数据库中获取的字符串值很少,例如

I have few string values which I am fetching from my database e.g

"1/4","2/3"

但是在显示为Android ListView内容时,我需要将其显示为0.250.66.

But while displaying as Android ListView contents I need to display it as 0.25,0.66.

现在,我不想拆分字符串,然后将单个字符串隐蔽为数字,然后 然后将它们除以得到结果.

Now I don't want to split the string and then covert to individual strings to numbers and then divide them to have result.

有人知道像Double.valueOfparseDouble这样的直接函数吗?

Does anyone know, any direct functions like Double.valueOf or parseDouble kind?

为什么您不想拆分字符串,然后将单个字符串隐蔽为数字,然后将其拆分为结果" ?

我不知道有任何内置函数可以做到这一点,所以是最简单的解决方案:

I am not aware of any built-in function to do that so the simplest solution:

double parse(String ratio) {
    if (ratio.contains("/")) {
        String[] rat = ratio.split("/");
        return Double.parseDouble(rat[0]) / Double.parseDouble(rat[1]);
    } else {
        return Double.parseDouble(ratio);
    }
}

它还涵盖了比率为整数的情况

It also covers the case where you have integer representation of ratio

parse("1/2") => 0.5
parse("3/7") => 0.42857142857142855
parse("1") => 1.0