How to make one digit after decimal point? - java

Searching how to make two digit after decimal point as below
$ = (double) (((int)($ * 100)) / 100.0);
Anyone can help to how to make "one digit" after decimal point ?
thanks a lot

What about this:
$ = (double) (((int)($ * 10)) / 10.0);
Note: edited after the comment.
If you need java and rounding instead of truncate try this:
import java.lang.Math;
double a;
a = ((double) (round(a*10))) / 10.0;
This will shift left the dot of one position, round to the nearest integer and then shift the dot back to the right one position.
Edited second time:
What you need is still unclear.
If you are fine with truncate as before:
double $=1.24*(double)amount;
$ = (double) (((int)($ * 1000)) / 1000.0);
outelc.setText("ELC(1.24)= " + Double.toString($) + " /pc");
If you need rounding:
double $=1.24*(double)amount;
$ = (double) ((round($ * 1000)) / 1000.0);
outelc.setText("ELC(1.24)= " + Double.toString($) + " /pc");

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.

Related

Concatenating a double in a string truncates

For a variable double spread = 0.135; I'm writing
"" + Math.round(spread * 10000) / 100 + "%"
This is attempting to round to 1 basis point. (100 basis points = 1 %).
But it doesn't include any decimal part.
Why?
This is yet another variant of integer division truncates; albeit slightly more deeply buried than normal.
Math.round(spread * 10000) returns an long. Dividing that by 100 will truncate the result to a long.
Your fix? Use 100.0 as the divisor. Then the expression is computed in floating point.
When you divide a long by an int you get a long which is a whole number. The simple solution is to divide by a double. Try
Math.round(spread * 10000) / 100.0 + "%"
or
Math.round(spread * 1e4) / 1e2 + "%"
Round() returns a long. The div operation is thus a long value.

Recursively create apollonian gaskets [With solution]

Apollonian gaskets = They are planar fractals generated from triples of circles, where each circle is tangent to the other two. In his drawing of the gasket, we start with two externally tangent circles which diameter is D1 and D2. Then we add a third circle which diameter is D1+D2 and to which the two original circles are internally tangent. This is the first generation of circles.
Each subsequent generation of circles is constructed by applying the following scheme:
For any three circles A, B C of any previous generations which are tangent to each other a new circle is constructed which is tangent to A,B,C. The new circle must differ from all circles constructed so far. When a generation is complete, i.e no other circle can be added, then the next generation of circles can start being constructed.
There is an additional stopping rule which prevents from generating infinitesimally small circles. A circle can be added to the gasket if and only if the lenght of its diameter is least minD which is a fixed positive value.
Input consists of one line with three decimal numbers D1, D2 and minD. The number are separated by spaces. The format is usual decimal format (see also the examples bellow) with no exponent part.
It holds that 1.0 ≤ D1, D2 ≤ 1000.0, 0.001 ≤ minD ≤ D1+D2.
Ouput consists of one text line containing two decimal numbers L1 and L2. L1 represents the sum of areas of all circles in the gasket except for the bigggest circle. L2 represents the sum of perimeters of all circles in tin the gasket except for the bigggest circle. Both output values are rounded to 6 decimal digits. Decimal digits must be always present in the output even if some of them are zeros.
Maximim output value is less than 107.
Input
17.000000 40.000000 1.000000
Output
2439.258588 835.263228
2
For given D1 and D2, I create this two circles like this (first iteration):
double D1 = 17.00;
double D2 = 40.00;
double minD = 1.00;
int i = 250, j = 350;
comp.addCircle(i, j, (int) D2, randomColor);
comp.addCircle(i + (int) D2 / 2 + (int) D1 / 2, j, (int) D1, randomColor);
comp.addCircle(i + (int) D1 / 2, j, (int) (D1 + D2), randomColor);
UPDATE:
So, solution is based on Descartes' theorem. We well work with radius, not diameter, and Curvature, with is 1/r.
We will use double for all calculation, but if you work with significantly small numbers, I would prefer BigDecimal. It will slow algorithm, and you should use external method for finding square root, because BigDecimal doesn't have any.
For given D1, D2, minD we modify code above for efficiency:
Some preparation:
double D1 = sc.nextDouble() / 2;
double D2 = sc.nextDouble() / 2;
minD = sc.nextDouble() / 2;
double D3 = D1 + D2;
So, first step looks like this:
Next step looks a little bit more complicated.
Assume we want to write a recursion to solve this problem, and according to Descartes' theorem, for given curvatures of three circles, tangent to each other, (pic. below)
, we could find curvatures of two circles, but for our purposes, we need only small one, so, we can simplify formula to
this.curve = a.curve + b.curve + c.curve + 2 * Math.sqrt(Math.abs(a.curve * b.curve + a.curve * c.curve + b.curve * c.curve));
Lets take a look at Apollonian gaskets again: try to play with it.
See? It is same gaskets, but with different start condition. And whats more important for us, is that it is symmetrical! So, we will calculate just a half, and then multiply result by two!
Lets write a recursion! Inputs will be curvatures of three circles. No output, we will use change our global variables.
double radius_sum = 0.0;
double square_radius_sum = 0.0;
void createAG(double a, double b, double c){
double n = a + b + c + Math.sqrt(a*b + a*c + b*c + 4.0);
if ((minD * n) < 1){
radius_sum += 2. / n; //Remember about symmetry?
square_radius_sum += 2. * (1. / n) * (1. / n); //Remember about symmetry?
createAG(a, b, n);
createAG(a, c, n);
createAG(b, c, n);
}
}
To find the result, we will use formulas to calculate area and perimeter of circle.
Perimeter is length of circumference and equal to .
Area is equal to , as you already know, because we already calculated it in previous step, otherwise we had to store every radius and do more calculations.
radius_sum = 2 * Math.Pi * radius_sum;
square_radius_sum = Math.Pi * square_radius_sum;
But we forget about our first two circles! Let's fix it!
radius_sum += D1*2 + D2*2;
square_radius_sum += D1*D1 + D2*D2;
radius_sum = 2 * Math.Pi * radius_sum;
square_radius_sum = Math.Pi * square_radius_sum;
And there is always a room for improvement. For example, to use IEEE 754 in better way, I assume you will use 1. / x instead of 1 / x.
Thank you!
P.S. Copyright! This task (text and first picture of Apollonian gasket) is created by teachers at CTU, for course ALG. Picture of formulas is from Wikipedia. Everything else is public domain, if not patented, registered e.t.c.
So, solution is based on Descartes' theorem. We well work with radius, not diameter, and Curvature, with is 1/r.
We will use double for all calculation, but if you work with significantly small numbers, I would prefer BigDecimal. It will slow algorithm, and you should use external method for finding square root, because BigDecimal doesn't have any.
For given D1, D2, minD we modify code above for efficiency:
Some preparation:
double D1 = sc.nextDouble() / 2;
double D2 = sc.nextDouble() / 2;
minD = sc.nextDouble() / 2;
double D3 = D1 + D2;
So, first step looks like this:
Next step looks a little bit more complicated.
Assume we want to write a recursion to solve this problem, and according to Descartes' theorem, for given curvatures of three circles, tangent to each other, (pic. below)
, we could find curvatures of two circles, but for our purposes, we need only small one, so, we can simplify formula to
this.curve = a.curve + b.curve + c.curve + 2 * Math.sqrt(Math.abs(a.curve * b.curve + a.curve * c.curve + b.curve * c.curve));
Lets take a look at Apollonian gaskets again: try to play with it.
See? It is same gaskets, but with different start condition. And whats more important for us, is that it is symmetrical! So, we will calculate just a half, and then multiply result by two!
Lets write a recursion! Inputs will be curvatures of three circles. No output, we will use change our global variables.
double radius_sum = 0.0;
double square_radius_sum = 0.0;
void createAG(double a, double b, double c){
double n = a + b + c + Math.sqrt(a*b + a*c + b*c + 4.0);
if ((minD * n) < 1){
radius_sum += 2. / n; //Remember about symmetry?
square_radius_sum += 2. * (1. / n) * (1. / n); //Remember about symmetry?
createAG(a, b, n);
createAG(a, c, n);
createAG(b, c, n);
}
}
To find the result, we will use formulas to calculate area and perimeter of circle.
Perimeter is length of circumference and equal to .
Area is equal to , as you already know, because we already calculated it in previous step, otherwise we had to store every radius and do more calculations.
radius_sum = 2 * Math.Pi * radius_sum;
square_radius_sum = Math.Pi * square_radius_sum;
But we forget about our first two circles! Let's fix it!
radius_sum += D1*2 + D2*2;
square_radius_sum += D1*D1 + D2*D2;
radius_sum = 2 * Math.Pi * radius_sum;
square_radius_sum = Math.Pi * square_radius_sum;
And there is always a room for improvement. For example, to use IEEE 754 in better way, I assume you will use 1. / x instead of 1 / x.
Thank you!
P.S. Copyright! This task (text and first picture of Apollonian gasket) is created by teachers at CTU, for course ALG. Picture of formulas is from Wikipedia. Everything else is public domain, if not patented, registered e.t.c.

how to reduce a latitude to 4 decimal places

This is my second post on this subject. I have found dozens of posts on this subject and not a single solution that works. The location listener will provide you a latitude such as 3.734567E7. My goal is to reduce the accuracy of that latitude to four decimal places. I don't care if I truncate it or round it. the following code...
Double d = Double.parseDouble("3.734567E7");
NumberFormat fmtr = new DecimalFormat("###.####");
String f = fmtr.format(d);
Log.w(getClass().getName(), "result using DecimalFormat = " + f );
d = (double) Math.round(d * 10000.0) / 10000.0;
Log.w(getClass().getName(), "result using math round = " + d );
f = d.toString();
Log.w(getClass().getName(), "result string using math round = " + f );
produces three lines:
37345670
3.734567E7
3.734567E7
none of this processing has any affect on the number.
when I had to do this in C# on my windows phone app I did the following...
myExecution.latitude = Math.Round(newLatitude, 4); It took less than a minute of my time. I have over a weeks time trying to figure out how to do the same thing in java. the Java math.round, oddley enough, has no way to specify how many decimal places you desire to round to making it totally usless as far as I can understand.
I realize that scientific notation is only supposed to be a way of displaying values and does not have anything to do with how an amount is stored internally. This makes this problem all the more perplexing.
Can anyone modify the code above to make it round to 4 decimal places?
(but you can't change the 1st line of code. It must be specified in scientific notation. If you specify it in decimal notation it works wonderfully.
thanks, Gary
3.734567E7 means 3.734567 x 107 which is 37,345,670. So there are no decimals to round...
If you want 3.734600E7, you can use Math.round(d / 1000) * 1000).
One simple way:
System.out.println(String.format("%.4f", 1.23456789));
Output:
1.2346 (or 1,2346 depending on your locale)
Update: to show the rounding

Java's Math.Pow() function returning confusing results

I am working with the Math.pow() function, and have the following code:
double monthlyRate = (0.7d / 12);
int loanLength = 3;
double powerTest = Math.pow(1.00583, 36);
double powerResult = Math.pow((1 + monthlyRate),(loanLength * 12));
When this is run through the debugger, the values become
powerTest => 1.2327785029794363
powerResult => 7.698552870922063
The first is the correct one. I've stepped into the Math.pow function on both of the assignment lines. For powerTest,
the parameters for Math.pow are
double a => 1.00583
double b => 36.0
For powerResult, they are
double a => 1.0058333333333333
double b => 36.0
I know that this is an issue with the way floating point math is performed by the machine, I'm just not sure how to correct it. I tried doing the following before the calculation with poor results:
monthlyRate = Math.round(monthlyRate * 1000) / 1000;
1 + monthlyRate is 1.0583..., not 1.00583.
Your expression 0.7d/12 = 0.0583, in the powerTest expression you are using 0.00583.
I think part of the problem is that 0.7/12 ~ 0.058333, and 1.0583 > 1.00583. My bet is this is the true source of your discrepancy, the floating point adjustments have little to do with it.
Obviously a such big difference in the resut(1.23... and 7.70) is not related to the way floats are coded but more than you made a mistake somewhere
1+0.7/12 = 1.0583 is different from 1.00583 ;-).
Math.round(monthlyRate * 1000) / 1000.0;
You were using integer division.
On Java you can use BigDecimal to perform money operations resulting on accurate numbers: it is the Sun/Oracle recommended way to store money numbers.
// I'm using Strings for most accuracy
BigDecimal monthlyRate = new BigDecimal("0.7").divide(new BigDecimal(12));
int loanLength = 3;
BigDecimal powerTest = new BigDecimal("1.00583").pow(36);
BigDecimal powerResult = BigDecimal.ONE.add(monthlyRate).pow(loanLength * 12);
monthlyRate = ((double)Math.round(monthlyRate * 1000)) / 1000;

Rounding a double

Hey guys, I am trying to round to 3 decimal places.
I used the following code.
this.hours = Round(hours + (mins / 60), 3);
But it's not working.
Where have I gone wrong?
Thanks
You can use this function:
public static double Round(double number, int decimals)
{
double mod = Math.pow(10.0, decimals);
return Math.round(number * mod ) / mod;
}
First thing is that all your variables are int so the result of your division is also an int, so nothing to Round.
Then take a look to: How to round a number to n decimal places in Java
If mins is an integer, then mins / 60 will result in an integer division, which always results in 0.
Try changing from 60 to 60.0 to make sure that the division is treated as a floating point division.
Example:
int hours = 5;
int mins = 7;
// This gives 5.0
System.out.println(Math.round(1000 * (hours + (mins / 60 ))) / 1000.0);
// While this gives the correct value 5.117. (.0 was added)
System.out.println(Math.round(1000 * (hours + (mins / 60.0))) / 1000.0);
if mins is an integer you have to divide through 60.0 to get a floating number which you can round
try using like follow
this.hours = Round(hours + (((double)mins) / 60), 3);
You can't. Doubles don't have decimal places, because they are binary, not decimal. You can convert it to something that does have decimal places, i.e. a base-ten number, e.g. BigDecimal, and adjust the precision, or you can format it for output with the facilities of java.text, e.g. DecimalFormat, or the appropriate System.out.printf() string.

Categories