Double Accuracy - java

I need some help, this is the code I'm referring to:
int myId;
my Id = 20113275l
int numLet;
numLet = 6;
double doubleResult;
doubleResult = 10000 + (80 + ((myId - 123456) / ((numLet + 20)*(numLet + 20)) ));
System.out.println("Expression 5: " + doubleResult);
According to my calculator, the answer should be 39650.7, but when I run the program it's giving me 39650.0
Can anyone explain what's going on here?

You should use double values only to get the wanted result in this case :
int myId;
myId = 20113275;
int numLet;
Becomes
double myId = 20113275.0;
double numLet;
And here is the output :
Expression 5: 39650.73816568047

You're getting integer division, because none of your parameters are double. The result of dividing two integers is an integer. And your type is an int (adding an l at the end promotes to long). Anyway, cast one of the terms to a double and you'll get the result you expect. For one decimal of precision you can use formatted output. Something like,
public static void main(String[] args) {
int myId = 20113275; // <--- Not a long.
int numLet = 6;
double doubleResult = 10000 + //
(80 + ((myId - 123456) / (double) ((numLet + 20) * (numLet + 20))));
System.out.printf("Expression 5: %.1f%n", doubleResult);
}
Output is (as you requested)
Expression 5: 39650.7

Related

Change double decimal spaces depending on int value

i want to change the decimal spaces of an double, depending on the int value that i use. I Figured out, that i can change the decimal spaces "manually" by changing to 10 or 1000 and so on, but i dont know how to accomplish this, other than changing said values in the code.
My second quest is how to round double values for example 19.657 up to 19.66, or 19.652 down to 19.65 .
Note :
WITHOUT the use of imports and only the default package
I use Java with Eclipse as my IDE
Thank you in advance for your effort :)
double x = 19.657821456;
int y = 3;
x = x*10;
x = (double)((int) x);
x = x /10;
You can use the DecimalFormat class to format your doubles.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(10));
>10.00
This will also round values if they exceed the amount of decimals you specified
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(19.657));
>19.66
You can use Decimal Formate to format double value
Example:
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + df.format(input)); //3.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("\ndouble (RoundingMode.DOWN) : " + df.format(input)); //3.14
df.setRoundingMode(RoundingMode.UP);
System.out.println("double (RoundingMode.UP) : " + df.format(input)); //3.15
}
Output :
double : 3.14159265359
double : 3.14
double (RoundingMode.DOWN) : 3.14
double (RoundingMode.UP) : 3.15
Variable number of digits after decimal. Basically same idea as code in question, just using Math methods, calculating the multiplier as needed (10 or 1000 in question):
public static double round(double value, int digits) {
if (digits < 0)
throw new IllegalArgumentException("digits must be non-negative: " + digits);
var mult = Math.pow(10, digits);
return Math.rint(value * mult) / mult;
}
If not allowed to use Math (standard lib, no import needed), we can calculate the multiplier in a loop and use an offset of 0.5 to round to the nearest integer (negative for negative numbers):
public static double round(double value, int digits) {
if (digits < 0)
throw new IllegalArgumentException("digits must be non-negative: " + digits);
var mult = 1.0;
for (var i = 0; i < digits; i++) {
mult *= 10;
}
var offset = value>0 ? 0.5 : -0.5;
return (int) (value * mult + offset) / mult;
}
Be warned that these methods will only work for small number of digits (intermediate results eventually exceeding the integer or even the double value range)
not tested - please test code before using

How to divide numbers by 10 but doesnt take the reminder [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
What do I do if I want to divide only tens? for example I have 16 when I divide it to 10 it will only answer 1 if I do 23 it will give me 2, like what I want to do is like diving 20(example) and 10 and it is ignoring the 6 in 26.
Integer values ignore decimal places in division:
int num = 236;
int div = num / 10;
int remainder = num % 10;
System.out.println("div = " + div);
System.out.println("remainder = " + remainder);
You can however use float or double instead though to get those decimal placed and then optionally round the result back to an integer.
double withDecimal = (double) num / 10.0;
int rounded = (int) Math.round(withDecimal);
System.out.println("withDecimal = " + withDecimal);
System.out.println("rounded = " + rounded);
Integer division in Java truncates decimals (hence the name). In order to maintain the decimals you have to make at least one of the variables a double or float like so:
double x = 16 / 10.0; //1.6
double y = 23 / 10.0; //2.3
Step 1: get the reminder by using number % 10;
Step 2: substract the reminder from the original number and store the result in a variable
Step 3: now divide the new number by 10.
public static void main(String []args){
int number = 33;
int reminder = number % 10;
number = number - reminder;
System.out.println(number / 10);
}

How do I force a number with unknown digits behind the decimal mark? [duplicate]

This question already has answers here:
How to merge two int(s) into a double in JAVA?
(6 answers)
Closed 6 years ago.
Is there a way to force a number to be placed behind the decimal mark of a number?
Say I have a number = 2, and another number = 23. Is there a way for me to force 23 into 0.23, so that when I add the numbers I end up with 2.23? And is there a way to do this when the number of digits in the second number, in this case 23, are unknown?
EDIT:
I realize this was badly written. I am currently working on a program that converts from imperial units to metric units. Part of the code looks like this:
double feet = nextDouble();
double inches = nextDouble();
double heightInMeters = (feet + (inches/10)) / 3.2808;
The problem with this code is that I anticipate that the user only enters a value <0, 9> for feet. Is there a way to force the input for inches to something like 0.x where x = inches so that it doesn't matter if the number is greater than 9?
Would be lovely if it was possible without using toString() and parseInt().
You can get the number of digits in an integer, i, using:
1 + Math.floor(Math.log10(i))
(not ceil(log10(i)), since that calculates that 1 has zero digits)
You then need to divide i by 10 to the power of that number:
i / Math.pow(10, 1 + Math.floor(Math.log10(i)))
e.g.
23 / Math.pow(10, 1 + Math.floor(Math.log10(23))) == 0.23
Ideone demo
Alternatively, if you think those floating point operations log and pow are too expensive, you can determine the number of digits with a loop:
int d = 1;
while (d < i) d *= 10;
then
System.out.println(i / (double) d);
(noting that you need to cast at least one of the numerator or denominator to a floating point type, otherwise it will use integer division).
Try parsing to double like this, from a string:
Option 1
try
{
int n = 2;
int decimal = 23;
String full = Integer.toString(n) + '.' + Integer.toString(decimal);
double val = Double.parseDouble(full);
} catch (Exception e) //Or whatever exception
{
//Code
}
Option 2
Of course, there are simpler methods, like this:
try
{
int n = 2;
int decimal = 23;
double val = Double.parseDouble(n + "." + decimal);
} catch (Exception e) //Or whatever exception
{
//Code
}
I personally would recommend the solution directly above, since it is the simplest, and requires the least code.
Live Example for Second Option
Simple implementation using Strings:
public class Mainclass {
public static void main(String[] args) {
Integer num = 1546;
Integer num2 = 2;
String s = num.toString();
s = "0." + s;
Double d = Double.parseDouble(s);
System.out.println(num2+d ); // 2.1546
}
}

Can val be used as variable in Java?

Is the program legal or not?
I am trying to correct out a statement that will print the value of 3 divided by 2.
I know this isn't correct.
System.out.print("The result is" + 3 / 2 + ".")
This is my answer.
System.out.print("The result is" + val + ".")
double val = 3 / 2
Is my answer correct or no? If not, how would I call upon the number?
You can do the following
double val = 3.0 / 2;
System.out.print("The result is" + val + ".");
the value val must be declared before it is printed. Also you need to make one of the number of type double so when the division is done, the answer is a double also. Else you lose precision.
the following is also valid:
double val = 3 / 2.0;
System.out.print("The result is" + val + ".");
if you do double val = 3 / 2; then 3/2 division is made with two integers which also give another integer. So 3/2 should give 1.5 but since we are only diving integers, it will omit the .5 and only give 1. Then 1 is casted as a double and becomes 1.0.
What you have is mostly correct:
float val1 = 3;
float val2 = 2;
float val= val1/val2;
System.out.println("The result is " + val + ".");
Remember your semicolons.
Also... You are correct to use a double (or float). Because otherwise your answer will be truncated.
EDIT:
Actually... I come to find that trying to do the operation in one shot still truncates the answer. It isn't correct unless both the values are set as floats. Then, run the math.
Here is proof: online java compiler
You need to declare first the variables. And if you want fraction numbers you need to do that with them. Need " ; " at the end of every statement. If you try it out in eclipse it will sign error to you when you don't write it where it need to be.
float num1 = 3;
float num2 = 2;
float val = num1 / num2;
System.out.print("The result is" + val + ".");
// Another way:
double num1 = 3;
double num2 = 2;
double val = num1 / num2;
System.out.print("The result is" + val + ".");
This should work:
double val = 3.0 / 2;
System.out.print("The result is" + val + ".");
Edit:
This is a case of integer division. When division is performed between two integers (here 3 and 2), the output is an integer and the fractional part gets trimmed off. So,3/2 will yield 1 which since you assign to a double variable, becomes 1.0.
When I do 3.0/2, 3.0 is a double value. The output here is a double value too i.e. 1.5; the fractional part is retained. Hence, my solution works.

How to divide 1 by 25(1/25) and get result .04 in java [duplicate]

This question already has answers here:
Fahrenheit to Celsius conversion yields only 0.0 and -0.0
(5 answers)
Closed 8 years ago.
It returns 0 if performed with plain BODMAS operation.
I have something like this:
int mbUsed=1;
int mbTotal=25;
int percent=(mbUsed/mbTotal)*100;
1/25 will return 0, since int division can't return fractions.
You can cast to double for floating point division :
int percent=(int) ((double)mbUsed/mbTotal)*100;
Or if you want a more accurate result :
double percent = ((double)mbUsed/mbTotal)*100;
If you want to stay with int division, you can change the order of the operators :
int percent = (100*mbUsed)/mbTotal;
The int data type in Java contains whole values. You should instead store your values in the double or float data types, as they can contain decimal points.
Here you can see an example:
public static void main(String[] args) {
int iVal1 = 1;
int iVal2 = 25;
int iVal3 = iVal1 / iVal2;
System.out.println("Integer storage, int variables: " + iVal3);
double dVal1 = iVal1 / iVal2;
System.out.println("Double storage, int variables: " + dVal1);
double dVal2 = (double) iVal1 / (double) iVal2;
System.out.println("Double storage, double variables: " + dVal2);
}
Which outputs:
Integer storage, int variables: 0
Double storage, int variables: 0.0
Double storage, double variables: 0.04
Notice how the values you are dividing also have to have at least double precision. In my example I simply type cast them to a double (seeing as they are whole numbers, it will make no difference), but you could also store them in double data types as well.
You can also use BigDecimal, so for other ratio's You can manipulate scale:
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
This is especially recommended for currencies.
BigDecimal dividend= BigDecimal.ONE;
BigDecimal divisor = new BigDecimal(25);
BigDecimal result = dividend.divide(divisor );
You might also consider just using doubles for your values mbUsed and mbTotal.
Example:
double mbUsed = 1;
double mbTotal = 25;
double percent = (mbUsed * 100)/mbTotal;
You could even add a decimal format, in case the numbers for mbUsed and mbTotal change.
Example:
DecimalFormat df = new DecimalFormat("#.00");
Then, you can use df.format(percent) in a System.out.println statement to display the percentage rounded to two decimal points.
Here is an example of some code that compiles as it should:
double mbUsed = 1;
double mbTotal = 25;
double percent = (mbUsed * 100)/mbTotal;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("The number used: " + df.format(mbUsed));
System.out.println("The total number: " + df.format(mbTotal));
System.out.println("The percentage used is: " + df.format(percent) + "%.");
This outputs:
The number used: 1.00
The total number: 25.00
The percentage used is: 4.00%
I hope this works well for you!

Categories

Resources