JAVA.BIGDEC.FLOAT

Do not construct BigDecimal objects from floating-point literals

Vulnerability and risk

Floating-point values may not represent decimals precisely and lead to unexpected outcomes when provided to BigDecimal() as a decimal literal.

Mitigation and prevention

Do not parse floats into BigDecimal, use strings or ints/longs. Provide floating-point decimal literal values to as a string.

Vulnerable code example 1

Copy
package com.klocwork;

import java.math.BigDecimal;

public class JAVA_BIGDEC_FLOAT_POSITIVE_1 {
    public static void test(String args[]) {
        System.out.println(new BigDecimal(0.1));
    }
}

Vulnerable code example 2

Copy
package com.klocwork;

import java.math.BigDecimal;

public class JAVA_BIGDEC_FLOAT_POSITIVE_2 {
    public static void test(String args[]) {
        System.out.println(new BigDecimal(7.321E-3));
    }
}

Vulnerable code example 3

Copy
package com.klocwork;

import java.math.BigDecimal;

public class JAVA_BIGDEC_FLOAT_POSITIVE_3 {
    public static void test(String args[]) {
        System.out.println(new BigDecimal(2f));
    }
}

Fixed code example

Copy
package com.klocwork;

import java.math.BigDecimal;

public class JAVA_BIGDEC_FLOAT_NEGATIVE {
    public static void test(String args[]) {
        System.out.println(new BigDecimal(0));
    }
}

External guidance