Sunil kumar
Sunil kumar

Reputation: 337

How can I prevent decimals being rounded when using DecimalFormat?

Can anyone help how can i prevent rounding decimal value.

DecimalFormat df = new DecimalFormat();

Object[] arrayRowResult = (Object[]) rowResult;
String a=df.format(arrayRowResult[0]) // [0] contain decimal(2,10) but format results rounded value
String b=df.format(arrayRowResult[1]) // [1] contain decimal(2,14) but format results rounded value

How can i prevent round off.

Upvotes: 3

Views: 5379

Answers (5)

Srikanth Josyula
Srikanth Josyula

Reputation: 904

You need to add df.setRoundingMode(RoundingMode.DOWN);

    double a = 980.199999;
    
    DecimalFormat df = new DecimalFormat("#,##0.00");
    df.setRoundingMode(RoundingMode.DOWN);
    String as = df.format(a);
    System.out.println(as);

This is will even add 2 decimal point for integers if you don't need you can change DecimalFormat

Output: 980.19

Upvotes: 0

Fedrick Kigodi
Fedrick Kigodi

Reputation: 1

package com.mkyong.test;

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class TestDouble {

    private static DecimalFormat df2 = new DecimalFormat(".##");

    public static void main(String[] args) {

        double input = 32.123456;
        System.out.println("double : " + input);
        System.out.println("double (default) : " + df2.format(input));

        df2.setRoundingMode(RoundingMode.UP);
        System.out.println("double (UP) : " + df2.format(input));

        df2.setRoundingMode(RoundingMode.DOWN);
        System.out.println("double (DOWN) : " + df2.format(input));

    }

}

Copy Output

double : 32.123456
double (default) : 32.12
double (UP) : 32.13
double (DOWN) : 32.12

Upvotes: 0

Kowser
Kowser

Reputation: 8261

Have you tried following?

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

Upvotes: 1

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(0);
df.setMaximumFractionDigits(2);
// .... your code

This will still round the numbers having more than two fraction digits -- change that value as you need it.

Upvotes: 3

SJuan76
SJuan76

Reputation: 24780

http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int)

and

http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#setMinimumFractionDigits(int)

Of course, both methods need that the precision is known a priori (it is not useful if it can have an arbitrary number of decimals).

Upvotes: 0

Related Questions