java - 只显示小数点后两位

标签 java android number-formatting

如何得到只有小数点后两位的double值。

例如

如果

i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));

此代码生成5.81403333

但我只想要5.81

那我该怎么办?

最佳答案

使用 DecimalFormat .

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

代码 fragment -

double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));

输出 -

5.81

关于java - 只显示小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959424/

相关文章:

java - 错误:Module 'com.squareup.assertj:assertj-android-recyclerview-v7:1.1.1' depends on one or more Android Libraries but is a jar

ios - NSFormatter 用于在 Swift 3 中将英语数字转换为波斯语或阿拉伯语数字

ios - 使用 Swift 的双重格式

javascript - 格式化从电子表格中读取的数字

java - EJB 3 RemoteInterface 类在查找期间强制转换异常

java - java执行器服务是命令设计模式的实现吗?

Android Activity 识别无法正常工作

java - 通过从每个集合中取一个值来计算一对的集合

java - 为什么我的 NumberFormatException 没有被我的 try-catch 捕获?

android - 如何在android中使用数据绑定(bind)实现Switch