界: Code Quality

程式碼品質不佳,會導致無法預料的行為。從使用者的角度來看,這通常表現為可用性不佳。對於攻擊者而言,這提供了以意想不到的方式向系統施加壓力的機會。

Code Correctness: String Comparison of Float

Abstract
比較浮點值與 String 物件並不可靠,所以不應該這樣做。
Explanation
若要比較浮點值與 String 物件,通常必須先透過 Double.toString() 之類的函數將浮點值變更為 String 物件。根據浮點變數的類型和值,在轉換為 String 物件時,它可能是「NaN」、「Infinity」、「-Infinity」,有特定含零的行尾小數位數,或是可能包含指數欄位。如果轉換為十六進位字串,表示法也會大為不同。

範例 1:以下將比較浮點變數與 String


...
int initialNum = 1;
...
String resultString = Double.valueOf(initialNum/10000.0).toString();
if (s.equals("0.0001")){
//do something
...
}
...
References
[1] NUM11-J. Do not compare or inspect the string representation of floating-point values CERT
[2] Standards Mapping - CIS Azure Kubernetes Service Benchmark 1
[3] Standards Mapping - CIS Amazon Elastic Kubernetes Service Benchmark 4
[4] Standards Mapping - CIS Amazon Web Services Foundations Benchmark 1
[5] Standards Mapping - CIS Google Kubernetes Engine Benchmark normal
[6] Standards Mapping - Common Weakness Enumeration CWE ID 398
desc.dataflow.java.code_correctness_string_comparison_of_float