You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Java中如何将String转为Double/Float并保留两位小数

Android Java中String转Double/Float并保留两位小数

一、String转Double并保留两位小数

首先得把String转换成Double类型,这里必须处理NumberFormatException(如果输入的String不是合法数字的话),之后再通过格式化工具保留两位小数。

方法1:使用DecimalFormat

String strValue = "123.456";
double doubleValue;
try {
    // 将String转为Double
    doubleValue = Double.parseDouble(strValue);
    // 格式化规则:#.##保留两位小数,若要强制补0用0.00
    DecimalFormat df = new DecimalFormat("#.##");
    // 格式化后转回Double,也可以直接使用格式化后的String结果
    double formattedDouble = Double.parseDouble(df.format(doubleValue));
    System.out.println(formattedDouble); // 输出123.46
} catch (NumberFormatException e) {
    // 处理字符串无效的情况
    e.printStackTrace();
}

方法2:使用String.format()

String strValue = "78.9";
try {
    double doubleValue = Double.parseDouble(strValue);
    // %.2f表示保留两位小数,返回String类型,如需Double再转换
    String formattedStr = String.format("%.2f", doubleValue);
    double formattedDouble = Double.parseDouble(formattedStr);
    System.out.println(formattedDouble); // 输出78.90
} catch (NumberFormatException e) {
    e.printStackTrace();
}

二、String转Float并保留两位小数

逻辑和转Double一致,只是把Double.parseDouble替换成Float.parseFloat。注意Float是单精度浮点数,精度低于Double,格式化方式通用。

方法1:DecimalFormat实现

String strValue = "45.1234";
float floatValue;
try {
    floatValue = Float.parseFloat(strValue);
    DecimalFormat df = new DecimalFormat("#.##");
    float formattedFloat = Float.parseFloat(df.format(floatValue));
    System.out.println(formattedFloat); // 输出45.12
} catch (NumberFormatException e) {
    e.printStackTrace();
}

方法2:String.format()实现

String strValue = "9.876";
try {
    float floatValue = Float.parseFloat(strValue);
    String formattedStr = String.format("%.2f", floatValue);
    float formattedFloat = Float.parseFloat(formattedStr);
    System.out.println(formattedFloat); // 输出9.88
} catch (NumberFormatException e) {
    e.printStackTrace();
}

提示:如果仅需展示保留两位小数的文本,不需要转回数值类型的话,直接使用DecimalFormat或String.format的String结果即可,避免额外的精度转换问题。

内容的提问来源于stack exchange,提问作者Nikhil S Marathe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:10:05