Format double to 2 decimal places [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
I am trying to Format my double value to exact 2 decimal places and it seems to working fine, here is the code i am trying
final NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.DOWN);
df.format(value)
Till now everything is working, but i need to return double value as it is being used for other calculations and i tried
Double.parseDouble(df.format(value))
with big decimal like
BigDecimal price = new BigDecimal(df.format(number));
but it is not working as expected
like 18.50 is being converted as 18.5
Though this is not an issue with calculations but i need to show amount on the UI where i have to show exactly up to 2 decimal places.
Is there any was i can handle it in java class or i have to take care in JSP with JSTL

This is what BigDecimal is made for!
BigDecimal number = new BigDecimal(123.456);
// set 2 fraction digits
// Note that setScale() does not change the original,
// but returns a new BigDecimal.
number = number.setScale(2, RoundingMode.DOWN);
// get string representation
String text = number.toPlainString();
// get double value
double dbl = number.doubleValue();
And use BigDecimal for other calculations as well if you can.

Related

How would I make a double value have a trailing zero in java. My program deals with currency [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
Round a double to 2 decimal places [duplicate]
(13 answers)
What data type to use for money in Java? [closed]
(11 answers)
Closed 3 years ago.
How would I make a double value have a trailing zero in java. My program deals with currency.
Ex. How do I to make 9.5 to 9.50?
For currencies, it would be better to use BigDecimal class which doesn't lose precision. You can define the precision as scale parameter.
If you want to display 9.50 to the user, use
String.format("%.2f", decimalValue)
where 2 is the number of decimal places you want to display.
Assuming that you need to convert a double to a String with two decimal places, you have to use a DecimalFormat:
DecimalFormat df = new DecimalFormat("#0.00");
double doubleValue = 9.5d;
String stringValue = df.format(doubleValue); // "9.50"
But when you are dealing with currency, it's better to deal with integers/longs/BigIntegers of the lowest possible amount (1 cent, 1 satoshi, etc) to avoid floating point errors, so keep that in mind.
If you're dealing with a currency, use the currency and internationalisation features of Java:
public static void main(String[] args) {
double iii = 9.5;
NumberFormat format = NumberFormat.getCurrencyInstance();
NumberFormat formatUS = NumberFormat.getCurrencyInstance(Locale.GERMANY);
System.out.println("Format currency (default) : " + format.format(iii));
System.out.println("Format currency (Germany) : " + formatUS.format(iii));
}
This produces:
Format currency (default) : $9.50
Format currency (Germany) : 9,50 €

Value shrink while converting Double to Bigdecimal [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
My problem while I am converting Double to BigDecimal I am loosing original value.
My requirement like input would be like Double val = 10435383974769502920d and want to convert like 10435.383974769502920 but getting below output.
I have tried with Double BigDecimal..but no success
Double val = 10435383974769502920d;
System.out.println(BigDecimal.valueOf(val).movePointLeft(15));
output : 10435.383974769502
Double val = 10435383974769502920d;
A double simply can't hold that many digits. Doubles are limited to ~15 decimal digits of precision. It's not BigDecimal that's losing the extra digits; it's the double you're starting with.
>>> System.out.printf("%f\n", 10435383974769502920d);
10435383974769502000.000000
Construct the BigDecimal with a string to avoid losing precision.
String val = "10435383974769502920";
System.out.println(new BigDecimal(val).movePointLeft(15));

Rounding price number in java [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
How to Round Decimals to 2 Places after the Decimal Point (Java)
(4 answers)
Closed 7 years ago.
I'm new to java programming. I would like to round up a price to the nearest 2 decimal places with a multiple of 5.
Eg.
38.80 stays the same.
38.81 to 38.80.
38.82 to 38.80.
38.83 to 38.85.
38.84 to 38.85.
38.85 stays the same.
38.86 to 38.85.
38.87 to 38.85.
38.88 to 38.90.
38.89 to 38.90.
38.90 stays the same.
I tried the provided duplicates but they come out only to 1 decimal place.
Eg. 38.82 to 38.8.
This is my code:
import java.text.DecimalFormat;
public class RoundUp {
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("#.##");
double num = 38.84;
System.out.println(df.format(Math.round(num*10.00)/10.00));
}
}
I have looked into other model answers by experts in this web but none of them really answer my question. Setting into 2 decimal places, I'm using DemicalFormat. That I know, but rounding the number, let's say 38.83 to 38.85 and 38.87 to 38.90 is what I really want.
It is a rounding system that my country is using. Can check it out here.
**
This question has been answer by #Mureinik double rounded =
Math.round(num * 100.0 / 5.0) * 5.0 / 100.0;
**
I would recommend you to use BigDecimal instead of double when you are dealing with money.
And then it would be like
BigDecimal value = new BigDecimal(38.84);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP)
You can refer Javadocs for ROUND_HALF_UP and setScale

Round number with Math round: doesn't work [duplicate]

This question already has answers here:
Round number to only first decimal place
(3 answers)
Closed 8 years ago.
I wish I could understand how it is possible that is not rounded the decimal number obtained from the following code.
File path2 = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize2 = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
double result = availableBlocks * blockSize;
free = (Preference)this.findPreference("free_mem");
free.setSummary(Double.toString(result)+" GB");
In a code similar to this use this instruction and works
result = Math.round(result * 10) / 10d;
Why not work here and I still see a number with many decimal places?
If I understood your question right you need NumberFormat here:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(result);
This produces a number with 1 decimal places.
So if result is 6.6789 it will produce 6.7.
Related: Round number to only first decimal place
Just a note:
If you do this:
Math.round(result * 10) / 10d;
you basically say:
Multiply result with 10
Round the result
Then divide with ten.
When you got rid of the decimals at step 2. you got another bunch of decimals after the division.

How return only two decimals with float? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
What's the best practice to round a float to 2 decimals? [duplicate]
(7 answers)
Closed 9 years ago.
I've got a float value and i need to have only two decimals after comma. I'm using this code:
public static float getWhatINeed() {
StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
float total =
((float)statFs.getBlockCount() * statFs.getBlockSize()) / (1073741824);
return total;
}
And it returns for example: 12.552425 in a textview. I need display something like: 12.55 that is enough for me. I saw this:
String s = String.format("%.2f", 1.2975118);
somewhere but I can't use it in my case because I use a float value and I need to use float. How could I solve this?
There is no mechanism to limit the number of decimal points in a float. A float is a float and it has an "unlimited" number of decimals. The String display of a float may be limited to a format only showing a specific number of decimals.
If you really NEED 2 decimals, use BigDecimal
You basically have 4 options:
return a float and deal with the fact that there are n decimal places
format to a String (which means a lot of string parsing if you need to do calculation)
convert to use BigDecimal
convert to use int and assume that the ones digit represents hundredths.
Did you try:
new DecimalFormat("00.00").format(1.2975118);
You can try as follows
DecimalFormat df = new DecimalFormat("0.##");
float a=1.256f;
System.out.println(df.format(a));
}
Out put
1.26
After setting precision and get as a String You can canvert it back to float by
float f = Float.parseFloat(YourString);

Categories

Resources