-1

i'm trying to add float number but it's doesn't work well.

Result:
0.2
0.4
0.6
0.8
1.0
1.2
1.4000001

my code :

static public void add_order(Product d)
    {       
        Float tt = Float.parseFloat(text_price.getText().toString());       
        tt += Float.parseFloat(d.getPrice());
        text_price.setText(tt + "");
    }

any idea ?

Armanoide
  • 1,248
  • 15
  • 31
  • some reading: http://steve.hollasch.net/cgindex/coding/ieeefloat.html –  Aug 03 '13 at 14:13
  • Generally when working with money or any other values where you simply can't afford letting the computer do mistakes, *don't* use float or double. – Johan S Aug 03 '13 at 14:17
  • Can i have a exemple to convert a string number to BigDecimal pls? – Armanoide Aug 03 '13 at 14:23
  • 2
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) also `Can i have a exemple to convert a string number to BigDecimal pls` just use constructor with String argument like `new BigDecimal("12.34")` – Pshemo Aug 03 '13 at 14:24
  • The difference between float/double and BigDecimal is whether decimal fractions are specially supported. Float and double, for compactness and efficient hardware support, are based on binary fractions. BigDecimal, based on decimal fractions, is the right type to use if numbers that can be expressed as short, terminating decimal fractions are especially important. – Patricia Shanahan Aug 03 '13 at 15:36

1 Answers1

0

Doesn't seem like it is not working well to me, float is not made for exact results; do not use it in that context. Use an int or long and for example multiply by 100, then you have 2 digits that actually work.

From the terms in your code example I assume you're doing some currency work; if you have a requirement for different precisions, go for BigDecimal.

dst
  • 3,307
  • 1
  • 20
  • 27