如何在Java中将分数格式的字符串从小数转换为浮点数或浮点数? [英] How to convert from fraction formatted string to Decimal or Float in Java?

查看:956
本文介绍了如何在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

这篇关于如何在Java中将分数格式的字符串从小数转换为浮点数或浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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