Truncate a float and a double in java [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 1 year ago.
I want to truncate a float and a double value in java.
Following are my requirements:
1. if i have 12.49688f, it should be printed as 12.49 without rounding off
2. if it is 12.456 in double, it should be printed as 12.45 without rounding off
3. In any case if the value is like 12.0, it should be printed as 12 only.
condition 3 is to be always kept in mind.It should be concurrent with truncating logic.

try this out-
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(12.49688f));
System.out.println(df.format(12.456));
System.out.println(df.format(12.0));
Here, we are using decimal formatter for formating. The roundmode is set to DOWN, so that it will not auto-round the decimal place.
The expected result is:
12.49
12.45
12

double d = <some-value>;
System.out.println(String.format("%.2f", d - 0.005);

I have the same problem using Android, you can use instead:
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.DOWN);
but for this API Level 9 is required.
Another fast solution is:
double number = 12.43543542;
int aux = (int)(number*100);//1243
double result = aux/100d;//12.43

take a look with DecimalFormat() :
DecimalFormat df = new DecimalFormat("#.##");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator(',');
df.setDecimalFormatSymbols(dfs);

Check java.math.BigDecimal.round(MathContext).

Try using DecimalFormat and set the RoundingMode to match what you need.

Related

multiplying DecimalFormat number (no longer rounded properly)

I'm basically trying to use DecimalFormat to get to two decimal places. I'm taking two integer values then dividing them and casting to a double I've put in sample values below. When I do as below I get a value that is no longer to two decimal places. It seems to be when multiply by the 3 it loses it's rounding.
DecimalFormat df = new DecimalFormat("#.00");
double d = Double.parseDouble(df.format((double)5/6))*3;
System.out.println(d);
Can you let me know why this occurs and how to fix this?
In the statemet:
double d = Double.parseDouble(df.format((double)5/6))*3;
the formatting is not preserved (Double returns a double).
You could do, e.g.:
System.out.println(df.format(d));

Formatting Double to exactly 2 Decimal places IF required

I require a DecimalFormat or a better equivalent of representing a Double value (in Java) which could be:
25 or 25.5
I need for that to be represented as either a whole number (25) or to two decimal places if it has any (25.50). This is because i'm printing it out as money.
I have the following format already:
DecimalFormat decFormat = new DecimalFormat("##,###.##");
This works perfectly if the Double is a whole number; I get the output $25,000. Except if the value is 25,000.5; it prints $25,000.5 when I need it to be printed as $25,000.50. The problem is as stated in the docs:
# a digit, zero shows as absent
So essentially the last zero is dropped off since it is optional.
I cannot do:
DecimalFormat decFormat = new DecimalFormat("##,###.#0");
as that is not allowed.
How can I achieve this?
Note:
These questions are related but do not cover what I need specifically with the DecimalFormat. Most of the answers suggest using a BigDecimal or printf. Is this the best thing to do? I don't have to use DecimalFormat but prefer to since i've started on that path (lots of code everywhere already using it).
Best way to Format a Double value to 2 Decimal places
How do I round a double to two decimal places in Java?
Round a double to 2 decimal places
This is definitely a bit of a hack, but I don't know if the DecimalFormat syntax allows for anything better. This simply checks to see if the number is real, and formats based on the spec you asked for.
double number = 25000.5;
DecimalFormat df;
if(number%1==0)
df = new DecimalFormat("##,###");
else
df = new DecimalFormat("##,###.00");
System.out.println(df.format(number));
When you need to return Decimal Format value this works
import java.text.DecimalFormat;
/**
* #return The weight of this brick in kg.
*/
public double getWeight()
{
DecimalFormat df = new DecimalFormat("#.##");
double number = ( getVolume() * WEIGHT_PER_CM3 ) / 1000;
//System.out.println(df.format(number));
return Double.valueOf ( df.format( number ) );
}

Convert into 2 decimal points [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I have a code here that calculate a rate for payment. It works however certain value will result in numerous number of decimal points. I want the result to be converted into only 2 decimal point. How do I do this? below is the attached code:
double rateConv=(((new Double(4.4) * transaction.getAmount())/100)+(transaction.getAmount()+new Double(0.30)));
System.out.println(rateConv);
transaction.setCurrencyPsy(rateConv);
transaction.setUserId(getLoginUserProfile().getUserId());
transaction.setTransType(WalletConstant.TRANS_DEPOSIT);
transaction.setIsApproved(false);
transaction.setCreateDate(new Date());
transaction.setIsCiTrans(false);
transDAO.save(transaction,getLoginUserProfile(),getText("email.admin"));
if(transaction.getDepositType().equals(WalletConstant.DEPOSIT_WIREDTRANSFER)){
addActionMessage(getText("msg.success.tt"));
}else{
addActionMsg(getText("msg.success"));
}
transaction = new WalletTransaction();
} catch (Exception e) {
e.printStackTrace();
addActionErr(getText("Error in system.Please contact system's administrator."));
return ERROR;
}
execute();
return "paymount";
}
Thanks in advance
Use BigDecimal
BigDecimal bd = new BigDecimal(doubleValue);
bd = bd.setScale(2, RoundingMode.HALF_UP);
return bd.doubleValue();
Here RoundingMode.HALF_UP will round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
There are many ways of doing what you have asked for
1.
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
2.
double d = 1.234567;
System.out.printf("%1$.2f", d);
but I would never ever use double for money values anyways, I recommend you to take a look at BigDecimals
EDIT: look # Zeeshan ´s answer if you want to convert Double to Big Decimal.
but the best is to ONLY use Big Decimal for money values, then you will never have any rounding issues # converting.
Use DecimalFormat
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(rateConv));
Try like this:
double amount = 123;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(amount));

How to round 0.0 to 0.00 in java?

I have used the following function
float val=0.0;
DecimalFormat toTheFormat = new DecimalFormat("#.##");
float value=Float.valueOf(toTheFormat.format(val));
But its not suitable for all conditions like "0.0" still "0.0". Its not scale up to "0.00".
Use
DecimalFormat toTheFormat = new DecimalFormat("0.00");
to round to 2 significant digits
try
DecimalFormat toTheFormat = new DecimalFormat("#.00");
Your approach is mistaken. Rounding is a numeric operation that takes a number x and returns another number y which approximates x and has the property that the decimal expansion has only so many digits. Example:
0.123 --> 0.12
But 0.0 and 0.00 are the exact same numbers, there is no point in rounding. What you (maybe) want is to format a number in a certain way on output. For this, see the other answers.
If I use DecimalFormat toTheFormat = new DecimalFormat("#.00");
am getting output as .00 not 0.00
so this would be the correct code
DecimalFormat toTheFormat = new DecimalFormat("#0.00");

Java, rounding a double to two decimal places

I'm trying to round a double to the nearest two decimal places however, it is just rounding to the nearest full number.
For example, 19634.0 instead of 19634.95.
This is the current code I use for the rounding
double area = Math.round(Math.PI*Radius()*Radius()*100)/100;
I can't see where i am going wrong.
Many thanks for any help.
Well, Math.round(Math.PI*Radius()*Radius()*100) is long. 100 is int.
So Math.round(Math.PI*Radius()*Radius()*100) / 100 will become long (19634).
Change it to Math.round(Math.PI*Radius()*Radius()*100) / 100.0. 100.0 is double, and the result will also be double (19634.95).
You can use a DecimalFormat object:
DecimalFormat df = new DecimalFormat ();
df.setMaximumFractionDigits (2);
df.setMinimumFractionDigits (2);
System.out.println (df.format (19634.95));
Do you actually want want to round the value to 2 places, which will cause snowballing rounding errors in your code, or simply display the number with 2 decimal places? Check out String.format(). Complex but very powerful.
You might want to take a look at the DecimalFormat class.
double x = 4.654;
DecimalFormat twoDigitFormat = new DecimalFormat("#.00");
System.out.println("x=" + twoDigitFormat.format());
This gives "x=4.65". The difference between # and 0 in the pattern is that the zeros are always displayed and # will not if the last ones are 0.
The following example came from this forum, but seems to be what you are looking for.
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}

Categories