Gabriel Santos
Gabriel Santos

Reputation: 65

"Bug" in String.Format and Float

i have a code that convert float to string

total  = quant * valUnit;

lb_total.setText(String.format(Locale.US,"%.2f", total));

if total = 56.025(7.5 * 7.47) > 56.02

if total = 71.025(7.5 * 9.47) > 71.03

Why the first not rounds up?

I find the solution for my problem, i create a class to make this correctly.

import java.lang.Math;

// iniF   = value to be rounded
// posIni = number of max houses(EX: 7.45 * 7.999, max houses for this operation is five)
// posFin = number of houses after rounded
// EX: xx*.xxxxx -> xx*.xx    posIni = 5, posFin = 2
public class MyMath {
    public Float MyRound(Float iniF, int posIni, int posFin){
        Float result     = 0.00f;
        int resultTmp    = 0;
        int nCasas       = (int) Math.pow(10, posIni - 1);
        Float arredondaF = iniF * nCasas;

        for(int p = posIni; p > posFin; p--){
            resultTmp  = Math.round(arredondaF);
            arredondaF = (float) resultTmp / 10;
        }

        result = arredondaF / 10;

        return result;
    }
}

Upvotes: 0

Views: 71

Answers (1)

lurker
lurker

Reputation: 58324

It's due to internal precision difference, especially since those numbers are the result of a floating point operation. Internally, 56.025 is really something like 56.0249999998, and 71.025 is something like 71.025000000002. Floating point operations aren't exactly, mathematically precise in the computer due to binary/decimal conversion and bit resolution of values.

Here are examples taken from Ruby to illustrate:

irb(main):003:0> format("%.2f", 7.5 * 7.47)
=> "56.02"
irb(main):004:0> format("%.2f", 7.5 * 9.47)
=> "71.03"

Here I used much higher precision of the format, and you can see the what the values really are:

irb(main):007:0> format("%.15f", 7.5 * 9.47)
=> "71.025000000000006"
irb(main):008:0> format("%.15f", 7.5 * 7.47)
=> "56.024999999999999"

There are numerous posts on stackoverflow.com, in various forms, about this issue. Just do a form search on "floating point precision" or "floating point exact".

Upvotes: 1

Related Questions