2

I'm finding a logarithm of value 1 which is equal to 0 not 0.0. When user enter any point values then it give exact answer. But the problem is Which Value Does Not Consist in points it give the answer of those value in points.I try parsing and Typecasting but nothing happen.Is there a function in Java which can Stop This.
This is my Code.

public class New {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double num = 0;
double result;
System.out.print("Value:");
num = s.nextDouble();
result = Math.log(num);

System.out.print("Answer:"+result);
}

}

Compiler Output:

Value:1
Answer:0.0
David Koelle
  • 20,726
  • 23
  • 93
  • 130

3 Answers3

1
System.out.print("Answer:" + (result == 0.0 ? "0" : result));
user489041
  • 27,916
  • 55
  • 135
  • 204
1

The 0.0 is how the double value representing 0 is printed by default. Also, the Math.log method returns a double. 0.0 is equal to the number 0. The logarithm, any positive base, of 1 is 0.

If you'd like not to print the decimal point if the result is an integer, then test if it's an integer.

if (result == (int) result)
{
    System.out.println((int) result);
}
else
{
    System.out.println(result);
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • `(result == (int) result)` will return true for any exact integer representation, ie. `double` 0, 1, or 2, but NOT `double` 3, since it can't be represented exactly. Just a caveat; it's not a perfect method for checking integer-ness. – Shotgun Ninja May 29 '15 at 17:28
  • @ShotgunNinja While one should generally be careful of `double` values that can't be represented exactly, `3` isn't one of them. `3` can be represented exactly as a `double`. – rgettman May 29 '15 at 17:31
  • Oh derp, I was thinking of simple fractions, not simple integers... – Shotgun Ninja May 29 '15 at 17:32
  • 1
    @rgettman Is it good way to use if else or typecast in this.Does Java has any function that can do this job. –  May 29 '15 at 17:40
  • Because you want 2 different output formats based on whether it's an integer, using if/else is good. You can use `Math.floor` and test whether the floor of the number is equal to the number. It's best to use the cast here. It's possible to use a `DecimalFormat` to control the output also. – rgettman May 29 '15 at 17:50
1

This isn't because of the internal representation or the value, or what it is equivalent to; this is because of how the double value 0 is displayed when rendered to a String (ie. by the code "Answer:"+result). The value under the hood returned from Math.log(1) is the double representation of a IEEE 754 positive zero, which for all intents and purposes is equivalent to the integer constant 0.

Shotgun Ninja
  • 2,540
  • 3
  • 26
  • 32