Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only two digit after decimal [duplicate]

How to get the double value that is only two digit after decimal point.

for example

if

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

this code generating 5.81403333.

But I want only 5.81.

So what shoud I do?

like image 435
URAndroid Avatar asked Jun 09 '12 08:06

URAndroid


People also ask

How do you double only show two decimal places?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places. However, we can't configure the rounding mode in String.

How do I show only 2 digits after a decimal in HTML?

parseFloat(num).toFixed(2);

How do I keep two digits after decimal in Excel?

By using a button: Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.

What is a number with 2 decimal places?

4.732 rounded to 2 decimal places would be 4.73 (because it is the nearest number to 2 decimal places). 4.737 rounded to 2 decimal places would be 4.74 (because it would be closer to 4.74). 4.735 is halfway between 4.73 and 4.74, so it is rounded up: 4.735 rounded to 2 decimal places is 4.74.


2 Answers

Use 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.

Code snippet -

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

Output -

5.81

like image 69
Subhrajyoti Majumder Avatar answered Sep 21 '22 22:09

Subhrajyoti Majumder


How about String.format("%.2f", i2)?

like image 40
dumazy Avatar answered Sep 19 '22 22:09

dumazy