private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int num = (Integer)this.jSpinner1.getValue();
int d = (Integer)this.jSpinner2.getValue();
int val = (num / d);
jTextField1.setText(String.valueOf(val));
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int num = (Integer)this.jSpinner1.getValue();
int d = (Integer)this.jSpinner2.getValue();
int val1 = (int) ((double)num / (double)d);
jTextField2.setText(String.valueOf(val1));
}
I am creating a program that uses a numerator and denominator the uses buttons to display integer and double value. The program works but it does not show decimals. It usually goes to the closest whole number. Basically what I need is help with getting decimals to show up in the output. http://imgur.com/WdnxgrH
You are explicitly declaring your output variable as int.
Return a double value, or for better precision, a BigDecimal.
Example
BigDecimal output = new BigDecimal(num)
.divide(new BigDecimal(d), BigDecimal.ROUND_HALF_UP);
Related
I'm getting exponential value in the result of expression where I'm adding double with long.
package com.testing;
import java.util.Date;
public class TypeCasting {
public static void main(String[] args) {
long varA = 100000;
long varB = 3000000;
double logVarA = Math.log10(varA); // 5.0
double logVarB = Math.log10(varB); // 6.477121254719663
long timeStampInSec = new Date().getTime() / 1000;
System.out.println(timeStampInSec); // 1552543503
double totalValue = logVarA + logVarB + timeStampInSec;
System.out.println(totalValue); // 1.5525435144771214E9
double finalScoreDampingFactor = 1000;
double finalScore = totalValue / finalScoreDampingFactor;
System.out.println(finalScore); // 1552543.5144771214
}
}
In totalValue variable why I'm getting 1.5525435144771214E9 value and when I'm deviding it with 1000, getting 1552543.5144771214.
Can any body please explain ?
A number has the same value, regardless of how it's represented. What you see printed as a String is just a representation of the number.
The JVM has decided, for whichever reason, that the number should be printed in exponential form. If you want to force it to print it differently, you can use printf.
double totalValue = logVarA + logVarB + timeStampInSec;
System.out.printf("%f%n", totalValue); // 1552547672.477121
The notation EX means "times 10 to the power of X".
So the original number was 1552543514.4771214.
1.5525435144771214E9
is 1552543514.... divided by 1000 is 1552543....
Is it possible that you misinterpreted the 1.5525435144771214E9 ?
import java.util.Scanner;
public class Test1C
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer between 1 and 50: ");
double quo;
int num = reader.nextInt();
for(double a = 1; a <= num; a++)
{
quo = (num / a);
System.out.println(quo);
}
}
}
This is the code I currently am making to evaluate the list of quotients based on what number was inputted. Now the only thing my brain keeps farting on about is how to convert the whole numbers that are currently decimals into integers. However, the doubles (ex: 1.333) that are printed by this code are fine as is. I just can't figure out how to convert the whole number decimals (ex: 12.0) into whole number integers. Can someone help me?
yes you can :
String s = "1.333";
double d = Double.parseDouble(s);
int i = (int) d;
or
String s="1.333";
int i= new Double(s).intValue();
you can do like that .
Double d = new Double(1.25);
int i = d.intValue();
System.out.println("The integer value is :"+ i);
There is no general way to detect whether a double is truly an integer and a comparison of double and double or int must, generally, be handled with much care, but for the range of numbers in your program (and the upper bound could be raised considerably), this will work as you want:
for(double a = 1; a <= num; a++) {
double quo = num/a;
int iquo = (int)quo;
if( iquo == quo ){
System.out.println(iquo);
} else {
System.out.println(quo);
}
}
How to convert a double value to int doing the following:
Double If x = 4.97542. Convert to int x = 4.
Double If x = 4.23544. Convert to int x = 4.
That is, the answer is always rounding down.
If you explicitly cast double to int, the decimal part will be truncated. For example:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
Moreover, you may also use Math.floor() method to round values in case you want double value in return.
If the double is a Double with capital D (a boxed primitive value):
Double d = 4.97542;
int i = (int) d.doubleValue();
// or directly:
int i2 = d.intValue();
If the double is already a primitive double, then you simply cast it:
double d = 4.97542;
int i = (int) d;
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
The double value is 420.5 and the application prints out the integer value of 420
Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean
I think I had a better output, especially for a double datatype sorting.
Though this question has been marked answered, perhaps this will help someone else;
Arrays.sort(newTag, new Comparator<String[]>() {
#Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
Say I have the following three constants:
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:
// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);
Please let me know what I'm doing wrong.
Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])
NumberUtils.max(int[])
Math.max only takes two arguments, no more and no less.
Another different solution to the already posted answers would be using DoubleStream.of:
double max = DoubleStream.of(firstValue, secondValue, thirdValue)
.max()
.getAsDouble();
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
I have a very simple idea:
int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.
Regards,
Norbert
Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().
If you don't like that you can always create your own method for it...
public class test {
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String args[]) {
double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
}
public static Object multiMax(Object... values) {
Object returnValue = null;
for (Object value : values)
returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
: (value instanceof Double) ? (Double) value
: (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
: (returnValue instanceof Double) ? (Double) returnValue
: (Float) returnValue)) ? value : returnValue)
: value;
return returnValue;
}
}
This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.
It might also be throwing an error since there is no such thing as "MY_DOUBLE2".
int first = 3;
int mid = 4;
int last = 6;
//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));
Is there a Java Library function which can be used to truncate a number to an arbitrary number of decimal places?
For Example.
SomeLibrary.truncate(1.575, 2) = 1.57
Thanks
Try setScale of BigDecimal like so:
public static double round(double d, int decimalPlace) {
BigDecimal bd = new BigDecimal(d);
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
Incredible no one brought this up yet, Java API has had DecimalFormat for ages now for this exact purpose.
For most numbers, you won't be able to get an exact representation of xxx.yyyy unless you use a decimal class with guaranteed accuracy, such as BigDecimal.
There's one in commons-math. Check out http://commons.apache.org/math/apidocs/org/apache/commons/math/util/MathUtils.html:
public static double round(double x,
int scale)
It's implemented using BigDecimal, and is overloaded to allow specifying a rounding method, so you can use it to truncate, like this:
org.apache.commons.math.util.MathUtils.round(1.575, 2,
java.math.BigDecimal.ROUND_DOWN);
Update:
In the last version (Math3), this method is in the class Precision.
org.apache.commons.math3.util.Precision.round(double x, int scale, int roundingMethod)
Simply remove the fractional portion
public double trunk(double value){
return value - value % 1;
}
Use this simple function
double truncateDouble(double number, int numDigits) {
double result = number;
String arg = "" + number;
int idx = arg.indexOf('.');
if (idx!=-1) {
if (arg.length() > idx+numDigits) {
arg = arg.substring(0,idx+numDigits+1);
result = Double.parseDouble(arg);
}
}
return result ;
}
I just want to add to ubuntudroid's solution.
I tried it and it wouldn't round down, so I had to add
df.setRoundingMode(RoundingMode.FLOOR);
for it to work.
here is a short implementation which is many times faster than using BigDecimal or Math.pow
private static long TENS[] = new long[19];
static {
TENS[0] = 1;
for (int i = 1; i < TENS.length; i++) TENS[i] = 10 * TENS[i - 1];
}
public static double round(double v, int precision) {
assert precision >= 0 && precision < TENS.length;
double unscaled = v * TENS[precision];
if(unscaled < Long.MIN_VALUE || unscaled > Long.MAX_VALUE)
return v;
long unscaledLong = (long) (unscaled + (v < 0 ? -0.5 : 0.5));
return (double) unscaledLong / TENS[precision];
}
Delete the assert'ions to taste. ;)
Actually, this sort of thing is easy to write:
public static double truncate(double value, int places) {
double multiplier = Math.pow(10, places);
return Math.floor(multiplier * value) / multiplier;
}
Note that it's Math.floor, because Math.round wouldn't be truncating.
Oh, and this returns a double, because that's what most functions in the Math class return (like Math.pow and Math.floor).
Caveat: Doubles suck for accuracy. One of the BigDecimal solutions should be considered first.
To do it 100% reliably, you'd have to pass the argument as string, not as floating-point number. When given as string, the code is easy to write. The reason for this is that
double x = 1.1;
does not mean that x will actually evaluate to 1.1, only to the closest exactly representable number.
created a method to do it.
public double roundDouble(double d, int places) {
return Math.round(d * Math.pow(10, (double) places)) / Math.pow(10, (double)places);
}