Print Integer with 2 decimal places in Java - java

in my code i use integers multiplied by 100 as decimals (0.1 is 10 etc). Can you help me to format output to show it as decimal?

int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));

I would say to use 0.00 as format:
int myNumber = 10;
DecimalFormat format = new DecimalFormat("0.00");
System.out.println(format.format(myNumber));
It will print like: 
         
10.00
The advantage here is:
If you do like:
double myNumber = .1;
DecimalFormat format = new DecimalFormat("0.00");
System.out.println(format.format(myNumber));
It will print like:
0.10

You can printout a decimal encoded as an integer by divising by their factor (as a double)
int i = 10; // represents 0.10
System.out.println(i / 100.0);
prints
0.1
If you need to always show two decimal places you can use
System.out.printf("%.2f", i / 100.0);

Based on another answer, using BigDecimal, this also works:
BigDecimal v = BigDecimal.valueOf(10,2);
System.out.println(v.toString());
System.out.println(v.toPlainString());
System.out.println(String.format("%.2f", v));
System.out.printf("%.2f\n",v);
Or even your good old DecimalFormat will work with BigDecimal:
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(v));

You can try this:-
new DecimalFormat("0.00######");
or
NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);

you can use double instate of int.
it gives you a output with decimals.
and then you can divide with 100.

you can use double instate of int.
it gives you a output with decimals.
if you want the number to stand behind the dot. you can use this:
**int number=100;
double result;
result=number/(number.length-1);**
I hope you can you use this.

Related

Stop DecimalFormat with percentage sign from moving the decimal

Is there a way to prevent a DecimalFormat object from automatically moving the decimal place two places to the right?
This code:
double d = 65.87;
DecimalFormat df1 = new DecimalFormat(" #,##0.00");
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
System.out.println(df1.format(d));
System.out.println(df2.format(d));
produces:
65.87
6,587.00 %
But I'd like it to produce:
65.87
65.87 %
Surround your % with single quotes:
DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
By default when you use a % in your format string the value to be formatted will be first multiplied by 100. You can change the multiplier to 1 using the DecimalFormat.setMultiplier() method.
double d = 65.87;
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
df2.setMultiplier(1);
System.out.println(df2.format(d));
produces
65.87 %
This is how I do it:
// your double in percentage:
double percentage = 0.6587;
// how I get the number in as many decimal places as I need:
double doub = (100*10^n*percentage);
System.out.println("TEST: " + doub/10^n + "%");
Where n is the number of decimal places you need.
I know this isn't the cleanest way but it works.
Hope this helps.

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

Rounding a Double to 2dp

I am currently trying to write a program which rounds a "double" variable to two decimal places.
I have the method:
DecimalFormat df = new DecimalFormat("#.00");
However, when I apply the method:
double x = df.format(y-z);
I get an error telling me a "double" was expected but a "string" was found.
Any suggestions as to how to fix this?
Thanks!
Try this
#Test
public void test() {
int f = 100;
double d = 123.456;
double temp = d * f;
double rounded = Math.round(temp);
double to2dp = rounded / f;
Assert.assertEquals(123.46, to2dp, 0.00001);
}
The f = 100 is fro 2dp. You would use f = 10 for 1dp etc
If you are using doubles to store/calculate currency values, then you will likely find yourself in a world of pain with rounding. Been there, done that, got the scars.
I highly recommend that you use BigDecimal values for ALL currency values, and do not even involve doubles in the instantiation. Always use the String constructor.
See related questions here and here.
In a comment on my other answer, Gary Rowe has suggested the use of Joda Money as a solution.
Now while this may be a fine product, and I have to admit that I have not tried it, I am a bit concerned about the following example in their documentation:
// multiplies by 3.5 with rounding
money = money.multipliedBy(3.5d, RoundingMode.DOWN);
Now this is an interesting example because they have used a double amount which can be represented exactly using double precision.
To illustrate this, let's take the following unit test as an example:
double d1 = 3.5d;
BigDecimal bd1 = new BigDecimal(d1);
System.out.println("BD version of " + d1 + " = " + bd1);
BigDecimal bd2 = new BigDecimal("10000000");
BigDecimal bd3 = bd2.multiply(bd1);
System.out.println("Result in bd3 = " + bd3);
This yields the following output:
BD version of 3.5 = 3.5
Result in bd3 = 35000000.0
However, if you change the '3.5d' to '3.4d', you get a very different result:
BD version of 3.4 = 3.399999999999999911182158029987476766109466552734375
Result in bd3 = 33999999.999999999111821580299874767661094665527343750000000
Now the Joda Money classes may deal with this (somehow), but introducing any double precision numbers into the mix is fraught with danger.
Gary, perhaps you could comment about the result of a similar calculation in Joda Money.

Show decimal of a double only when needed

I got this problem with double (decimals).
When a double = 1.234567 Then I use String.format("%.3f", myString);
So the result is 1.234
But when my double is 10
The result will be 10,000
I want this to be 10
Is their a way to say that he only needs to show the decimals when it is "usefull"?
I saw some posts about this, but that was php or c#, couldn't find something for android/java about this (maybe I don't look good).
Hope you guys can help me out with this.
Edit, for now I use something like this: myString.replace(",000", "");
But I think their is a more "friendly" code for this.
The DecimalFormat with the # parameter is the way to go:
public static void main(String[] args) {
double d1 = 1.234567;
double d2 = 2;
NumberFormat nf = new DecimalFormat("##.###");
System.out.println(nf.format(d1));
System.out.println(nf.format(d2));
}
Will result in
1.235
2
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
Copy from Here.
Try it
double amount = 1.234567 ;
NumberFormat formatter = new DecimalFormat("##.###");
System.out.println("The Decimal Value is:"+formatter.format(amount));

Categories