Formatting a number with correct decimal scale - java

I need to format a number with scale of 2 decimal places. The original number may be a whole number or a number with three decimal places. However the result should be formatted to have commas and also two decimal places always regardless of whether the original number is whole number or having decimal places.
When original num = 56565656.342 ==> I need 56,565,656.34
When original num = 56565656 ==> I need 56,565,656.00
When original num = 56565656.7 ==> I need 56,565,656.70
I am using the following code which is formatting the code but its failing to add the two decimal places in the above 2 & 3 cases.
String originalNumber = "56565656.7";
BigDecimal b = new BigDecimal(originalNumber).setScale(2, BigDecimal.ROUND_HALF_UP);
String formattedNumber = NumberFormat.getInstance().format(b);
Please let me know if there is any way to accomplish this in efficeint way.
Thanks in advance.

Take a look at the DecimalFormat class.
Alternatively you can setScale method from the BigDecimal Class.
BigDecimal bg1 = new BigDecimal("56565656.342");
BigDecimal bg2 = new BigDecimal("56565656.00");
BigDecimal bg3 = new BigDecimal("56565656.70");
DecimalFormat df = new DecimalFormat("###,###.00");
System.out.println(df.format(bg1.doubleValue()));
System.out.println(df.format(bg2.doubleValue()));
System.out.println(df.format(bg3.doubleValue()));
System.out.println(bg1.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(bg2.setScale(2, BigDecimal.ROUND_HALF_UP));
System.out.println(bg3.setScale(2, BigDecimal.ROUND_HALF_UP));
Yields:
56,565,656.34
56,565,656.00
56,565,656.70
56565656.34
56565656.00
56565656.70
EDIT: Also forgot to mention: If you are after precision, I would recommend you use the setScale method, using the .doubleValue() method will yield a double which can cause loss of precision.

Just use NumberFormat and specify the fraction digits, and rounding method, to print :
String [] originalNumbers = new String[] {
"56565656.342",
"56565656.7",
"56565656"
};
NumberFormat df = NumberFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.HALF_UP);
for (String number : originalNumbers) {
String formattedNumber = df.format(new BigDecimal(number));
System.out.println(formattedNumber);
}
Will print
56,565,656.34
56,565,656.70
56,565,656.00
** Edit **
DecimalFormat df = new DecimalFormat("#,###.00");
Will produce the exact same result with the given code above.

DecimalFormat class would do it for you.... You will have to specify appropriate format.

Related

I want to keep my trailing zeroes when using DecimalFormat

The code below is my attempt to convert my three doubles into a format where they have four decimal places always (because I need to print them with four decimal places for what is meant to be a simple assignment), even if all the numbers after the decimal point in the original double are 0 - as in any whole number. I figured I might be able to use the setMinimumFractionDigits() method to prevent DecimalFormat from eliminating trailing zeroes - but it doesn't do the job: "3.0" still gets printed out instead of what I want: "3.0000". I realise that below my instances of this setMinimumFractionDigits() method are literally doing nothing.
(Numbers whose decimal places aren't all zeroes aren't a problem; the code is working as I want it to for them.)
........ Is there an easy fix? There may be; I don't understand very well the methods I'm using here.
double mean = mean(numbers);
double variance = variance(numbers, mean);
double sd = sd(variance);
DecimalFormat meanFormatted = new DecimalFormat("#.####");
meanFormatted.setMinimumFractionDigits(4);
mean = Double.valueOf(meanFormatted.format(mean));
DecimalFormat varianceFormatted = new DecimalFormat("#.####");
varianceFormatted.setMinimumFractionDigits(4);
variance = Double.valueOf(varianceFormatted.format(variance));
DecimalFormat sdFormatted = new DecimalFormat("#.####");
sdFormatted.setMinimumFractionDigits(4);
sd = Double.valueOf(sdFormatted.format(sd));
see this usage
double d = 12.3;
DecimalFormat meanFormatted = new DecimalFormat("#.0000");
System.out.println (meanFormatted.format (d));
Found a solution:
double mean = mean(numbers);
double variance = variance(numbers, mean);
double sd = sd(variance);
Formatter transform = new Formatter();
Formatter transform1 = new Formatter();
Formatter transform2 = new Formatter();
transform.format("%.4f", mean);
transform1.format("%.4f", variance);
transform2.format("%.4f", sd);
System.out.printf("\nMean = %s\n", transform);
System.out.printf("Variance = %s\n", transform1);
System.out.printf("Standard deviation = %s\n", transform2);

BigDecimal values wants set a new scale

I have a BigDecimal value, for example
BigDecimal bdVal = new BigDecimal("3.141592653");
I really want this value printed to be
dbVal: 3.141600000
What should I do for that ???
If you would like to round the value up to four decimal places, use
BigDecimal rounded = bdVal.setScale(4, RoundingMode.HALF_UP);
To print it with nine zeros, use this format:
DecimalFormat decFormat = new DecimalFormat("0.000000000");
String formatted = decFormat.format(rounded);
Demo.

Round Double value and exponential notation (java)

how to round "3.416436417734133 in "3.416436418" (nine positions after point) but also if i have "3.7578845854848E41" it round to "3.7578845855E41"? i'm trying to realyze a calculator..
You can use DecimalFormat, I am not sure about the other numbers but currently you have numbers which have single digit before the decimal point. So, check following example where you can format the double value. Note one more thing that you may need to change format pattern for your use case.
FOR EXAMPLE :
double d = 3.7578845854848E41;
double d2 = 3.416436417734133;
DecimalFormat f = new DecimalFormat("0.#########E0");
System.out.println(f.format(d));
System.out.println(f.format(d2));
OUTPUT :
3.757884585E41
3.416436418E0
//Replace E0 with space as format returns String
EDIT :
Because of your default locale. You can change local like this,
//Change locale
DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US);
DecimalFormat f = new DecimalFormat("0.#########E0", decimalFormatSymbols);
//And than use decimal format
You may use BigDecimal to add a "scale" to your double value :
Double d = 3.416436417734133;
BigDecimal round = new BigDecimal(d);
round = round.setScale(9, BigDecimal.ROUND_CEILING);
System.out.println(round);
You can use this code.
BigDecimal aDecimal = new BigDecimal(3.416436417734133);
BigDecimal another = aDecimal.setScale(9, aDecimal.ROUND_HALF_UP);
System.out.println("another: " + another);
System.out.println(new BigDecimal(3.7578845854848E41,new
MathContext(11,RoundingMode.CEILING)));

Multiply with two Decimal Place - Java

multiply the double Type number, from the output need to taken with two Decimal Place
double creditCardPercentage = 0.03;
String renewalEventAmount = "2144.60";
double expectedRenewalAmount = 0;
expectedRenewalAmount = Double.parseDouble(renewalEventAmount) * creditCardPercentage;
the output for the expectedRenewalAmount is 64.338, then how can we format the above output with two decimal
Expected:
64.33
You should use the BigDecimal class because it has built-in handling for floating point precision:
BigDecimal creditCardPercentage = new BigDecimal(0.03);
String renewalEventAmountString = "2144.60";
BigDecimal renewalEventAmount = new BigDecimal(renewalEventAmountString);
BigDecimal expectedRenewalAmount = renewalEventAmount.multiply(creditCardPercentage);
expectedRenewalAmount = expectedRenewalAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
System.out.println(expectedRenewalAmount); // prints 64.33
One of the advantages of using BigDecimal to handle the formatting is that it allows you to separate your code from your business logic, i.e. rounding down to 2 decimal places, from the view code which outputs the result to the user.
You could use NumberFormat.getNumberInstance().format(expectedRenewalAmount) which will use the system properties to format the value. You can also modify the NumberFormat, specifying the number of decimal places if you want.
Or you could use System.out.printf or String.format to format the value as well...
String value = String.format("%.2f", expectedRenewalAmount);
A couple answers have suggested printf; but if you don't want to print the answer right away, you can use String.format the same way:
String formattedString = String.format("%.2f", expectedRenewalAmount);
and now you can print out the result if you want, or you can display it in a Swing text window or change all the zeros to happy faces or do whatever else you like with the resulting string, which you can't do with printf.
You can use the printf() function with %f:
System.out.printf("%.2f", expectedRenewalAmount);
Here you can find a beautiful printf format cheat sheet by Alvin Alexander that might help you (and hopefully others) a lot.
Try this while printing:
System.out.printf("%.2f", expectedRenewalAmount);
You can use
DecimalFormat df = new DecimalFormat("#.00");
double creditCardPercentage = 0.03;
String renewalEventAmount = "2144.60";
double expectedRenewalAmount = 0;
expectedRenewalAmount = df.format(Double.parseDouble(renewalEventAmount) * creditCardPercentage);
you can use minimumFractionDigit to 0
public class Test {
public static void main(String[] args) {
System.out.println(format(14.0184849945)); // prints '14.01'
System.out.println(format(13)); // prints '13'
System.out.println(format(3.5)); // prints '3.5'
System.out.println(format(3.138136)); // prints '3.13'
}
public static String format(Number n) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(2);
return format.format(n);
}
}
please find below reference link.
Java: Use DecimalFormat to format doubles and integers but keep integers without a decimal separator

How to always round off upto 2 decimal places in java

I have tried the following code but it is not working in a particular case.
Eg: Suppose, I have a double value=2.5045 and i want it to be rounded off upto two decimal places using the below code.After rounding off, i get the answer as 2.5. But I want the answer to be 2.50 instead. In this case,zero is trimmed off. Is there any way to retain the zero so as to get the desired answer as 2.50 after rounding off.
private static DecimalFormat twoDForm = new DecimalFormat("#.##");
public static double roundTwoDecimals(double amount) {
return Double.valueOf(twoDForm.format(amount));
}
try this pattern
new DecimalFormat("0.00");
but this will change only formatting, double cannot hold number of digits after decimal poin, try BigDecimal
BigDecimal bd = new BigDecimal(2.5045).setScale(2, RoundingMode.HALF_UP);
Look at the documentation for DecimalFormat. For # it says:
Digit, zero shows as absent
0 is probably what you want:
Digit
So what you are looking for is either "0.00" or "#.00" as a format string, depending on whether you want the first digit before the period, to be visible in case the numbers absolute value is smalle than 0.
Try this
DecimalFormat format = new DecimalFormat("#");
format.setMinimumFractionDigits(2);
answer.setText(format.format(data2));
Try This
double d = 4.85999999999;
long l = (int)Math.round(d * 100); // truncates
d = l / 100.0;
You are returning a double. But double or Double are objects representing a number and don't carry any formatting information. Ìf you need to output two decimal places the point to do this is when you convert your double to a String.
use # if you want to ignore 0
new DecimalFormat("###,#0.00").format(d)
There is another way to achieve this . I have already posted answer in post
will just answer again here. As we will require rounding off values many times .
public class RoundingNumbers {
public static void main(String args[]){
double number = 2.5045;
int decimalsToConsider = 2;
BigDecimal bigDecimal = new BigDecimal(number);
BigDecimal roundedWithScale = bigDecimal.setScale(decimalsToConsider, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with setting scale = "+roundedWithScale);
bigDecimal = new BigDecimal(number);
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);
}
}
Output we will get is
Rounded value with setting scale = 2.50
Rounded value with Dividing by one = 2.50
double kilobytes = 1205.6358;
double newKB = Math.round(kilobytes*100.0)/100.0;
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("kilobytes (DecimalFormat) : " + df.format(kilobytes));
Try this if u are still getting the above problem

Categories

Resources