Java: Double Value Comparison

后端 未结 7 2118
日久生厌
日久生厌 2020-12-01 12:33

Do we need to be careful when comparing a double value against zero?

if ( someAmount <= 0){
.....
}
7条回答
  •  时光取名叫无心
    2020-12-01 13:04

    If you want to be really careful you can test whether it is within some epsilon of zero with something like

    double epsilon = 0.0000001;
    if      ( f <= ( 0 - epsilon ) ) { .. }
    else if ( f >= ( 0 + epsilon ) ) { .. }
    else { /* f "equals" zero */ }
    

    Or you can simply round your doubles to some specified precision before branching on them.

    For some interesting details about comparing error in floating point numbers, here is an article by Bruce Dawson.

提交回复
热议问题