hguser
hguser

Reputation: 36038

How to make sure a number with digits no more than 2 in java

I have some number values, and I want to make sure they hold up to 2 digits.

For example:

11.1233 --> 11.12
11.1    --> 11.1
123     --> 123

I have thought of using

String.format("%.2f",11.1233)

This works well for number more than 2 digits, but it will add extra 0 to the other, for example,it will cause the following result:

11.1 --> 11.10
123  --> 123.00

While I do not need the extra 0.

Is there an alternative?

Upvotes: 0

Views: 203

Answers (3)

Reimeus
Reimeus

Reputation: 159804

You could use DecimalFormat to suppress the non-significant digits

DecimalFormat format = new DecimalFormat("0.##"); 
format.setRoundingMode(RoundingMode.FLOOR);
System.out.println(format.format(11.1233));

Upvotes: 5

Leo Zhao
Leo Zhao

Reputation: 544

Try this:

NumberFormat nf = NumberFormat.getInstance();
double a = 11.1233;
double b = 11.1;
double c = 123;
System.out.println(nf.format(Double.parseDouble(String.format("%.2f",a))));
System.out.println(nf.format(Double.parseDouble(String.format("%.2f",b))));
System.out.println(nf.format(Double.parseDouble(String.format("%.2f",c))));

Upvotes: 1

Dan Ciborowski - MSFT
Dan Ciborowski - MSFT

Reputation: 7207

You could do something like this...

Double num = 11.111;
Double d = Math.Floor(num * 100) / 100

Depends if you want to store the other digits or not.

Upvotes: 1

Related Questions