rounding double in java [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I have a double valued diagonal matrix stored in a text file.
size(file)~410 Mo
I would like to reduce the size by rounding my double values.
If its a good idea, how to do it in java
0.1706524958886193=>0.17
I need to use this file later in matlab
when i try
dlmread(file) i get out of memory error

If you round the values you are throwing away precision. That may change the results you will get.
A better approach is to store only the diagonal items. There is no point in storing the n^2-n off-diagonal zeroes. Use the diag function to convert a vector into a diagonal matrix. http://www.mathworks.es/es/help/matlab/ref/diag.html
Even more efficient: store the numbers in a binary format instead of text.

Use DecimalFormat class to format the double value to your needs. For example, if you want to keep only 2 digits after decimal point use, "#0.00 and so on. DecimalFormat#format class returns String output which you can use to instantiate Double value.
from
import java.text.DecimalFormat;
public class Tester
{
public static void main(String arg[]) throws Throwable
{
double bigDouble=0.1706524958886193;
DecimalFormat df=new DecimalFormat("#0.00");
String numberString=df.format(bigDouble);
double smallDouble=new Double(numberString);
System.out.println(smallDouble);
}
}
Hope this helps...

Unless I'm misunderstanding the question you can do it like this:
double value = 0.1706524958886193;
value = (double)((int)(value*100))/100; // returns 0.17

Related

Math.pow() returns [float]E[int] [duplicate]

This question already has answers here:
Java and decimals E numbers
(2 answers)
Closed 8 months ago.
I was working on some problem in codeforces just for practice and the implementation I came up with is based on using the Math.pow() method in Java:
import java.io.*;
import java.util.*;
public class TestClass {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
long t = sc.nextLong();
//note that "MyScanner" is a pre-defined class for buffered input
//just to make it easier to call the methods
while (t-- > 0){
String m = sc.next();
long l = m.length(), n = Long.parseLong(m);
out.println(n - Math.pow(10, l-1));
}
out.close();
}
}
I/O example: the input can be too big, that's why I used the long datatype.
Input:
7
1
2
178
20
999999999
9000
987654321
Output:
0
1
78
10
899999999
8000
887654321
but instead I get this:
0.0
1.0
78.0
10.0
8.99999999E8
8000.0
8.87654321E8
as you can see, my solution seems to be correct, but the output was in different form.
The method you use has the following signature: static double pow(double a, double b). This means, the parameters will automatically be cast to double and it's return value is also a double.
There is no overload for a long return value so you will either have to cast the result manually to long with this: n - (long)Math.pow(10, l-1).
Edit: or use another solution like the BigInteger one, but be aware that BigInteger (and BigDecimal) only accepts int as exponent, not long and not BigInteger.
Math.pow won't guarantee 100% accuracy on large integer values beyond some threshold (see this question for details) because floats and doubles cannot accurately represent all integers supported by the long type. Therefore, I would recommend you to use a BigInteger, which also has a pow function and will give you correctly formatted results out of the box.

Why casting give me these weird results Java? [duplicate]

This question already has answers here:
Why converting from float to double changes the value?
(9 answers)
Closed 2 years ago.
This is the code
public static void main(String[] args) {
double x=5.6556464566546546546556465465465;
float y=(float)x;
double z= 1+y;
System.out.println(x+"\n"+y+"\n"+z);
}
}
and this is the output
5.6556464566546545
5.6556463
6.655646324157715
I can understand the value of x and y but z from where it got those fractional numbers after the 3??!
Thank you very much
Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.

How to round float to one decimal point without using DecimalFormat class in java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 6 years ago.
I was reading my old notes and found a question where a number with two decimal point is converted to a single decimal point. I looked around for answer and couldn't find it. I cannot keep it string as I have to return as a float and compare it.
Math.round was rounding it bad and ceil and floor was giving me error.
I came up with this solution.
public class floatRounding{
public static void main(String[] args){
//System.out.println(temperature((float)32.34));
// System.out.println(temperature((float)32.35));
if (temperature((float)32.34)<temperature((float)32.35)){
System.out.println("Here");
}
}
public static float temperature(float t){
float newt;
//newt=Math.round(t);
String tem=String.format("%.1f",(t+.009));
newt=Float.parseFloat(tem);
System.out.println(newt);
return newt;
}
}
Is there a better solution if I am not using decimal format like in this solution
How to round a number to n decimal places in Java
Thanks in advance. Please forgive if its a dumb question.
You could do something like this:
double x = 1.234;
double y = Math.round(x * 10.0) / 10.0; // => 1.2
System.out.println(y);
This rounds the decimal to the one decimal point, the code is much shorter. Hope this helps, if so accept the answer :)

Why is the area of a rectangle coming to 15 places of decimal? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
/*
Author: Noah Shaw
Date: 9/2/2016
Purpose: Calculate the area + perimeter of a rectangle
*/
public class Rectangle {
public static void main (String [] args){
//Display the Area
System.out.print("The Area of the Rectangle is ");
System.out.println((7.9 * 4.5));
//Display the Perimeter
System.out.print("The Perimeter of the Rectangle is ");
System.out.println((4.5 + 7.9) * 2);
}
}
The output is
The Area of the Rectangle is 35.550000000000004
The Perimeter of the Rectangle is 24.8
My question is why is my rectangle area not just 35.55?
Thanks for your time, sorry I'm still new to Java.
By default java is giving you the highest precision possible because you did not assigned any datatype to your area.
If you want to get answer unto 2 decimal places you have to format console
output.
Below is the sample code of your question:
public class Rectangle {
public static void main (String [] args){
//Display the Area
double area=7.9 * 4.5;
System.out.printf("The Area of the Rectangle is %2.2f",area);
//Display the Perimeter
System.out.print("The Perimeter of the Rectangle is ");
System.out.println((4.5 + 7.9) * 2);
}
}
Here printf is used instead of println and %2 is width of your answer and .2f is digits to use after decimal place.
if you work with floating point numbers you can work seamlessly with primitive as double data type, but about those numbers have to perform operations must be very careful because it may not go the right results.
Why? Because computers work in binary and when working with variables of type float or double precision make mistakes when working with values ​​that can not represent
How could it be otherwise, Java had already thought of this, and therefore provides BigDecimal, a class designed to solve these problems. But we still have a bad surprise in store.
The first thing to so one strip when using BigDecimal is the constructor BigDecimal (double), and this leads to the same problem. This constructor does is keep exactly the same representation as if working with a data type double. The solution is to work always with the constructor BigDecimal (String). BigDecimal's own documentation recommends it.
BigDecimal bd1 = new BigDecimal("8192.55");
in his case would be
BigDecimal bd = new BigDecimal(Float.toString((float) ((4.5 + 7.9) * 2))));
bd = bd.setScale(numberdecimals, BigDecimal.ROUND_HALF_UP);
//in his case would be considering whether to keep the number of decimal when zero
System.out.println(bd);
The reason is double will have the actual value. So, what you actually want is to print only two fraction digits. So, your task is formatting. Here is how you do that:
import java.text.NumberFormat;
public class NumberFormating {
public static void main(String[] args) {
NumberFormat twoFractionDigitsNumberFormat = NumberFormat.getInstance();
twoFractionDigitsNumberFormat.setMaximumFractionDigits(2);
System.out.println(twoFractionDigitsNumberFormat.format(2.123456789));
}
}
The answer isn't just .55 because there are still decimals that have been calculated after it. Use this;
double area = Math.round(area*100.0)/100.0;
System.out.println(area);
While finding area, you have two floating point numbers interacting with each other and floating point calculation is handle in a different way then integer calculation. In your case you have to format or cast the value to get two decimal points instead of a long string of decimals.
If you are interested in understanding how floating point calculation works, below I found two links which explain it:
http://floating-point-gui.de/basic/
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
I hope that helps.

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

Categories