Java 如何格式化字符串以显示两位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37524471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:25:25  来源:igfitidea点击:

how to format string to show two decimal places

javaandroidandroid-layout

提问by Zidane

I am facing a slight issue when trying to get two decimal places after pasring double to string and trying to format

在将 double 转换为字符串并尝试格式化后尝试获得两位小数时,我遇到了一个小问题

  pieChart.setCenterText("$" + "" + ""  +String.format( "% 1$ .2f", Double.toString(dataCost),""));

can anyone help me improve the above line of code so that it can display to two decimal places? You will also notice that I am trying to leave a space between the dollar sign and the value

谁能帮我改进上面的代码行,以便它可以显示到两位小数?你还会注意到我试图在美元符号和值之间留一个空格

采纳答案by mdDroid

You can use String.format("%.2f", d), your double will be rounded automatically

您可以使用String.format("%.2f", d),您的双精度值将自动四舍五入

pieChart.setCenterText("$ " + String.format("%.2f", d));

回答by Abhishek Patel

Try Like This

像这样尝试

 pieChart.setCenterText("$ " + String.format("%.2f", dataCost));

回答by Bhoomit_BB

Following code might help you

以下代码可能对您有所帮助

double a = 1.234567;
double a = 2;
NumberFormat nf = new DecimalFormat("##.##");
System.out.println(nf.format(a));
System.out.println(nf.format(a));

and the output will be

输出将是

1.23
2

it only show decimal places if needed, Enjoy! :)

如果需要,它只显示小数位,享受!:)

回答by Sarhad Salam

You can use DecimalFormat.

您可以使用十进制格式。

import java.text.DecimalFormat; 
DecimalFormat money = new DecimalFormat ("
    float val = 1245.235645f;
    double ans = Double.parseDouble(new DecimalFormat("##.##").format(val));

    System.out.println(ans);
.00"); System.out.println(money.format(dataCost));

回答by Sathish Kumar J

Try this.

尝试这个。

Package  : import java.text.DecimalFormat;

Note : ##.## means 2 digits will be displayed after the .(dot)

注意:##.## 表示 .(dot) 后会显示 2 位数字

##代码##

this should helps you.

这应该对你有帮助。