0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Java] なんか出力に「-0.0」って表示される

Last updated at Posted at 2020-05-17

きっかけは偶然に

IntelliJで気の向くままにjavaしてたら「ん?」ってなった

出力.コンソール
value = -0.0

結論

0を負の数で割ると-0.0になるっぽい

sample.java
public class Main {
    public static void main(String[] args) {
        double value = 0;
        System.out.println("value = "+value/-1);
        System.out.printf("value = %3.1f\n",value/-5);
    }
}
出力.コンソール
value = -0.0
value = -0.0

対処

if文つけるかぁ
割る値に対してif文で0代入すれば表示は正しく出る

sample.java
public class Main {
    public static void main(String[] args) {
        double value = 0;
        value /= -1;
        System.out.println("対処前 = "+value);
        if(value == 0) value  =0;
        System.out.println("対処後 = "+value);
    }
}
出力.コンソール
対処前 = -0.0
対処後 = 0.0

追記2020/05/26

-0が出る可能性のある計算に「+0」すると修正できるって

sample.java
public class Main {
    public static void main(String[] args) {
        double value = 0;
        value /= -1 +0;//+0すると-0にならない
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?