How to print a double with two decimals in Android

2019-01-08 09:27发布

This question already has an answer here:

Maybe this is a silly question, but I cannot guess how to solve it if it's not creating a method. Maybe there's a "natural way" to do it, like in C for example. Here's the problem:

I have a var:

double a;

And I want to show it only with 2 or 3 decimals. When I try to show it:

Text.setText("Value of a: " + String.valueOf(a));

It gives something like:

Value of a: 5.234966145

And i would want just

Value of a: 5.23

Without changing the real value of a so it shows the approximate number but works with the real number.

6条回答
Summer. ? 凉城
2楼-- · 2019-01-08 10:13

Before you use DecimalFormat you need to use the following import or your code will not work:

import java.text.DecimalFormat;

The code for formatting is:

DecimalFormat precision = new DecimalFormat("0.00"); 
// dblVariable is a number variable and not a String in this case
txtTextField.setText(precision.format(dblVariable));
查看更多
姐就是有狂的资本
3楼-- · 2019-01-08 10:18

For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-

DecimalFormat formater = new DecimalFormat("#.##"); 

2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-

DecimalFormat formater = new DecimalFormat("#.00"); 
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-08 10:20
yourTextView.setText(String.format("Value of a: %.2f", a));
查看更多
Emotional °昔
5楼-- · 2019-01-08 10:21
textView2.setText(String.format("%.2f", result));

and

DecimalFormat form = new DecimalFormat("0.00");
         textView2.setText(form.format(result) );

...cause "NumberFormatException" error in locale for Europe because it sets result as comma instead of point decimal - error occurs when textView is added to number in editText. Both solutions are working excellent in locale US and UK.

查看更多
小情绪 Triste *
6楼-- · 2019-01-08 10:25

You can use a DecimalFormat, or String.format("%.2f", a);

查看更多
时光不老,我们不散
7楼-- · 2019-01-08 10:26

use this one:

DecimalFormat form = new DecimalFormat("0.00");
etToll.setText(form.format(tvTotalAmount) );

Note: Data must be in decimal format (tvTotalAmount)

查看更多
登录 后发表回答