Leonz
Leonz

Reputation: 307

How can I remove last digit off a decimal number in Java?

For example, when I have 3.333 and when that code is executed, I need the number to be 3.33.

This is the code I have which should be doing that, but doesn't:

String number = Double.toString(first);
number = number.substring(0, string.length() - 1);
first = Double.parseDouble(number);

I tried doing it by converting the number to a string, cutting off last character and saving it into a double again. But it doesn't work. Instead of cutting off 1 digit, it cuts off 2, for example above it would return 3.3.

Is this method reliable and if yes, what can I do to fix it?

Also, is there a chance for this method to crash the program (only decimal numbers go through that code) and would there be a loss in precision?

Upvotes: 1

Views: 8420

Answers (6)

Aurimas
Aurimas

Reputation: 1

This code is reliable.

Double number = 3.333 ;
String  mano   = Double.toString(number);
String akmuo = mano.substring(0, mano.length() - 1);
number = Double.parseDouble(akmuo);
System.out.println(number);

Upvotes: -1

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27476

Use String.format:

String.format("%.2f", 3.333);

Or use BigDecimal:

new BigDecimal(3.333).setScale(2, RoundingMode.DOWN)

setScale sets how many decimal points you need. You can later do a toString() on the above BigDecimal and print it out.

Upvotes: 5

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

What about this:

double value = 3.333;
// Multiply it by 100, convert the result into an integer to trim 
// remaining decimals then divide it by 100d to get the result as double
double result = (int)(value * 100) / 100d;
System.out.println(result);

Output:

3.33

Upvotes: 2

Liam Duncan
Liam Duncan

Reputation: 144

The main problem with what you're trying to accomplish is that Doubles are always 64 bits of information. They are supposed to be as accurate as possible while representing abstract/irrational values and not intended to be manipulated in terms of that accuracy. They can't be trusted for exact values (the input value 1 might end up as 0.99999999998 when saved as a double or something to that effect). If you want an exact number, consider using ints in some capacity (ie you could make a fraction object that holds a numerator and denominator). The only time you should cut down a double is for printing, and that can only really be done with a String representation as you did above.

Upvotes: 0

Seek Addo
Seek Addo

Reputation: 1893

try this:

double d = 3.333;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
System.out.println(d);

output:

3.33

Upvotes: 1

SCouto
SCouto

Reputation: 7928

If you want always the same number of decimals the best solution as far as i know is this one:

DecimalFormat df = new DecimalFormat("#.00");

String formatedNumber = df.format(number);

Upvotes: 1

Related Questions