Regarding rounding off a value to certain decimal point - java

I was going through the class decimal format as I was trying format a decimal number in Java upto 2 decimal places or 3 decimal places.
I come up with this solution as shown below but please also let me know are there any other alternative that java provides us to achieve the same thing..!!
import java.text.DecimalFormat;
public class DecimalFormatExample {
public static void main(String args[]) {
//formatting numbers upto 2 decimal places in Java
DecimalFormat df = new DecimalFormat("#,###,##0.00");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
//formatting numbers upto 3 decimal places in Java
df = new DecimalFormat("#,###,##0.000");
System.out.println(df.format(364565.14));
System.out.println(df.format(364565.1454));
}
}
Output:
364,565.14
364,565.15
364,565.140
364,565.145
Please advise what are other alternatives that java provide us to achieve the same thing..!!

If you are bothered by re-defining your DecimalFormat, or if you suspect you'll be needing to do redefine many times, you could also do inline formatting with String.format(). Check the syntax for Formatter especially the Numeric sub-title.

Here is an alternative to round off...
double a = 123.564;
double roundOff = Math.round(a * 10.0) / 10.0;
System.out.println(roundOff);
roundOff = Math.round(a * 100.0) / 100.0;
System.out.println(roundOff);
The output is
123.6
123.56
Number of 0s while multiplying and dividing decides the rounding off.

Here is one method.
float round(float value, int roundUpTo){
float x=(float) Math.pow(10,roundUpTo);
value = value*x; // here you will guard your decimal points from loosing
value = Math.round(value) ; //this returns nearest int value
return (float) value/p;
}

Related

How to round numbers, remove "E"s from them and remove decimal points from whole numbers?

I have a crypto portfolio made, but the long percentage numbers or the "E"s instead of big numbers really tear up the design, like in this example:
How to fix them (round up to 2 decimal digits, remove E, remove .0 from 5)?
Try this:
Math.round(number * 100.0) / 100.0;
You can find plenty of other ways if you search.
Using the Double constructor, you can turn all of those strings into doubles.
String someNumberString = "1.2E5";
Double dNum = new Double(someNumberString);
You can do rounding as such:
double rounded = (Math.round(dNum * ROUND_TO_OFFSET) / ROUND_TO_OFFSET)
where ROUND_TO_OFFSET specifies the digit to round to. E.g. ROUND_TO_OFFSET= 100 rounds to the nearest 0.01. This has a disadvantage though. Math.round returns a long, so if your dNum * ROUND_TO_OFFSET produces a number that is larger or smaller than a long can hold, it will not work correctly.
You can format any double into a nice, easy to read format with the DecimalFormat class.
DecimalFormat decimalFormat = new DecimalFormat("#,##0.#####");
String formattedDouble = decimalFormat.format(someDouble);
This allows you to easily convert double values to strings that look like this:
1,234,567.89012
If you need more precision or numbers larger than what Long.MAX_VALUE can handle, you should checkout java's BigDecimal class.
BigDecimal provides it's own round method that allows you to specify what to round to. You can still use the DecimalFormat class by calling BigDecimal's doubleValue() function.

Rounding price to the nearest multiple of 5cent in java

I'm new to java programming. I would like to round up a price to the nearest 2 decimal places.
E.g.
38.82 into 38.80
38.87 into 38.90
38.85 stays the same.
I did the E.g. 1 and E.g. 2 but it comes out only 1 decimal place. E.g. 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 it 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.
And please everybody.. please don't change my question to a duplicate one. you think that its a duplicated one, please ask me for more info. I can ensure you that it is not a duplicated (I think...)
One way to do this is to convert the price to cents, divide by 5, round to, multiply by 5 again and convert back to dollars:
double rounded = Math.round(num * 100.0 / 5.0) * 5.0 / 100.0;
When you deal with money, you should avoid using float or double variables and use an integer datatype instead in order to avoid problems due to the fact that calculations with float or double values are not exact.
You could use the following solution (when dealing with int):
public static int roundUp(int cents) {
int centsMod5 = cents%5;
if (centsMod5 > 0) {
cents += (5 - centsMod5);
}
return cents;
}

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 ) );
}

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));
}

How to save decimal in java

Having the following code in Java:
double operation = 890 / 1440;
System.out.println(operation);
Result:
0.0
What I want is to save the first 4 decimal digits of this operation (0.6180). Do you know how can I do it?
Initialize your variable with an expression that evaluates to a double rather than an int:
double operation = 890.0 / 1440.0;
Otherwise the expression is done using integer arithmetic (which ends up truncating the result). That truncated result then gets converted to a double.
You can use the double literal d - otherwise your numbers are considered of type int:
double operation = 890d / 1440d;
Then you can use a NumberFormat to specify the number of digits.
For example:
NumberFormat format = new DecimalFormat("#.####");
System.out.println(format.format(operation));
You can also do something like this:
double result = (double) 890 / 1400;
which prints the following:
0.6180555555555556
You can check how to round up the number here
This is done using BigDecimal
import java.math.BigDecimal;
import java.math.RoundingMode;
public class DecimalTest {
/**
* #param args
*/
public static void main(String[] args) {
double operation = 890.0 / 1440.0;
BigDecimal big = new BigDecimal(operation);
big = big.setScale(4, RoundingMode.HALF_UP);
double d2 = big.doubleValue();
System.out.println(String.format("operation : %s", operation));
System.out.println(String.format("scaled : %s", d2));
}
}
Output
operation : 0.6180555555555556
scaled : 0.6181
BigDecimal, although very clumsy to work with, gives some formatting options:
BigDecimal first = new BigDecimal(890);
BigDecimal second = new BigDecimal(1440);
System.out.println(first.divide(second, new MathContext(4, RoundingMode.HALF_EVEN)));
double operation = 890.0 / 1440;
System.out.printf(".4f\n", operation);
If you really want to round to the first 4 fractional digits you can also use integer arithmetic by first multiplying the first number so its digits are shifted the right amount f places to the left:
long fractionalPart = 10000L * 890L / 1440L;
I'm using long here to avoid any overflows in case the temporary result does not fit in 32 bits.

Categories