Java module operator [duplicate] - java

This question already has answers here:
Rounding Errors?
(9 answers)
Closed 10 years ago.
Why does this code print 2.4099999999999997, instead of just 2.41
public class Main
{
public static void main(String args[])
{
double d = 5.55%3.14;
System.out.println(d);
}
}

The problem is not the modulo operator, but rather the nature of floating point numbers. A double cannot hold the precise value of either 5.55, 3.14 or 2.41, so you get an approximate answer.
To understand this better, try to write down the value of 1/3 as a decimal, when you only have limited space on the paper to write it. You'll end up with something like 0.33333, which is an approximation of the actual value. The same happens to 5.55 when you write it in binary - it turns into 101.10001100110011001100110011... which gets cut off somewhere to fit the space of the double.

import java.text.DecimalFormat;
double d = 5.55%3.14;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println( df.format( d ));
Add DecimalFormat
Edit:
You can also
double d = 5.55%3.14;
System.out.printf("%1$.2f", d);

Java double can have precision issues.
Why don't you try BigDecimal ?

the reason is that java doesn't do math the way we do. java uses binary numbers (from chapter 4 of Horstmann's big java book) so to a computer, 435 = 4 * 10^2 + 3 * 10^1 + 5 * 10^0
it does this because binary numbers (1 or 0) are easier to manipulate since switches in the computer are either on or off (1 or 0).
this results in occassional rounding issues. if you want to force it to round, then do things like use a decimal format, or if you just need the displayed value rounded you can use String.format or printf

Related

Formatting Double to String? [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 3 years ago.
String.format("%,.0f", 200000000000000000000000.0)
-> 199,999,999,999,999,980,000,000
why?
Understand the Double Data type - it is an approximation of amount and scale.
The Following assignment:
double d = 2.00000000000f;
will generate a value of 1.9999999 at times when printed. What you are seeing here is magnification of that. Double Data types also have a maximum (implementation-dependant) of how many places of significance they can support (upto 15 generally) - which is why the last 6 digits are all zeros (0)
For your particular solution, if you don't require Floating-point Data, stick to Integer.
It is because current processors(and most VMs) work like that if use default data types. Here it is explained in details
If you want precision use BigDecimal. This class is specifically intended for situations like this - to be used in currency related stuff and scientific calculations.
To format decimals in proper way Java has DecimalFormat
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(123456789.123);
System.out.println(format); // -> 123.456.789,123
Here is nice tutorial about it
Hope it helps.
My problem has been solved
String.format("%,.0f", BigDecimal( 200000000000000000000000.0, MathContext.DECIMAL64))

How to round a double to the nearest 10th place [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
public double hypotenuse()
{
//return Math.hypot(leg, leg); //returns 7.0710678118654755
//return 0.1 * Math.floor(Math.hypot(leg, leg) * 10); //returns 7.0
//return 0.1 * Math.ceil(Math.hypot(leg, leg) * 10); //returns 7.1000000000000005
return 0.1 * Math.round(Math.hypot(leg, leg) * 10); //returns 7.1000000000000005
}
I am trying to round to the nearest 10th place, so this number should round up to 7.1. Why does this method work with Math.floor but not with Math.round? Does anyone have any insight?
Thanks,
Sky
In regards to your answer to yourself, you don't want to convert an object of type A to type B, operate on it, and then convert it back to type A. Not if you can do anything else.
The following does what you want it to do:
public double hypotenuse()
{
return Math.round(Math.hypot(leg, leg) * 10) / 10.0;
}
I'm not entirely sure why. It would take some digging into what this compiles down to at the assembly level.
The real problem is that each double in Java only has a limited number of bits to store its decimal portion. There are an infinite number of possible real numbers in real life. There is no way you can represent every single real number with only 64 bits. This is why you should avoid floating point calculations in banking apps and software that requires the number to be exact. Multiplying a few doubles together can introduce quite a significant error margin in the calculation. See this explanation on another SO answer, which does a great job of explaining this further.
If you really need it to be exact, use BigDecimal.
Nevermind, this is what I found that works.
public double hypotenuse()
{
double hypot = Math.hypot(leg, leg);
String str = String.format("%1.1f", hypot);
hypot = Double.valueOf(str);
return hypot;
}
If this is for JS:
The Math.round() function returns the value of a number rounded to the nearest integer.

Why does Java give 2 - (0.10 + 1.05) = 0.8499...? [duplicate]

This question already has answers here:
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Floating point comparison [duplicate]
(5 answers)
Closed 9 years ago.
I'm fairly new to java but have some experience of coding (mostly PHP and some C++).
I'm having some trouble with calculations in my program. When I run the following code:
public class Test {
public static void main(String[] args) {
double number = 2 - (0.10 + 1.05);
System.out.println( number );
if( number < 0.85 ) System.out.println("to small");
}
}
My output is as follows:
run:
0.8499999999999999
to small
BUILD SUCCESSFUL (total time: 0 seconds)
I'm expecting 2 - ( 0.10 + 1.05 ) to be equal to 0.85 but for some reason it's not. Does anyone know why it would behave like this?
I'm using netbeans to code version 7.3.1 and jdk7u25 on Windows 8 if that is important. If there is anything else I should add please tell.
/Chris
That is because floating point numbers cannot represent all numbers in its range precisely, but takes something close. See:
http://introcs.cs.princeton.edu/java/91float/
That is also why you should never use float or double for storing monetary values.
Floating points numbers are in exponential form. There consists of mantissa and exponent field. Because of binary coding they do not cover exact numbers, but are close to them.
To have exact numbers use BigDecimal - http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html .
Because floating point numbers don't work like you think they do. In a nutshell, not all numbers can be precisely expressed in floating-point format, so you will see things like this when you use floating point data types.

Show only two digit after decimal [duplicate]

This question already has answers here:
how to convert double to 2 number after the dot? [duplicate]
(6 answers)
Closed 9 years ago.
How to get the double value that is only two digit after decimal point.
for example
if
i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));
this code generating 5.81403333.
But I want only 5.81.
So what shoud I do?
Use DecimalFormat.
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Code snippet -
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
Output -
5.81
How about String.format("%.2f", i2)?
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
Many other answers only do formatting. This approach will return value instead of only print format.
double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

Getting numbers after decimal Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange floating-point behaviour in a Java program
Why does JSP/JSTL division by 1000 sometimes give remainder?
I am trying to get the numbers after the decimal.
ex: 60.4 -> 0.4
Yet, when do
double a = 60.4 % 1;
it comes out to be 0.3999999999999986.
Why is this? And how could it be fixed?
Use fixed-point types
BigDecimal src = new BigDecimal("60.4");
BigDecimal a = src.remainder(BigDecimal.ONE);
You can use DecimalFormat to do your desired task.
OK here is how you can do: How to get the numbers after the decimal point? (java)
I think this is exactly what you are looking for. So essentially you can use:
double x = d - Math.floor(d);
OR
BigDecimal class for exact digits after decimal.

Categories

Resources