Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DecimalFormat does not rRoundUp correctly

Tags:

android

If the price for a dozen eggs is $1.50, DecimalFormat says the price for one egg is 0.12 instead of 0.13

If you went into the store and bought one egg twelve times, you would only pay $1.44

But if the price per dozen is 1.51, it gives the proper answer.

Apparently DecimalFormat uses this rule for rounding:

"RoundUp if the remainder is greater than (>) 5"

It should use this rule:

"RoundUp if the remainder is greater than OR EQUAL TO (>=) 5"

Below is a simple Android Project to demonstrate this.

If I am correct, what is the procedure for reporting this error to Google?

package Egg.Price;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MyEggPrice extends Activity 
{  double        xPricePerDozen, xPricePerEgg;
   NumberFormat  xMoney = new DecimalFormat("0.00");  
   TextView thePrice;
   String   xString;
      @Override
      public void onCreate(Bundle savedInstanceState) 
      {   super.onCreate(savedInstanceState);
           setContentView(R.layout.main_egg);

           xPricePerDozen   = 1.50; //user would normally enter via an EditText
           xPricePerEgg     = (xPricePerDozen / 12); 
           xString        = xMoney.format(xPricePerEgg); 
           thePrice       = (TextView) findViewById(R.id.the_price);
           thePrice.setText(xString);
        }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"    android:layout_height="fill_parent"
    >
<TextView   android:text="Price Per Egg"
    android:layout_width="fill_parent"    android:layout_height="30dip" 
    />
<TextView   android:id="@+id/the_price"
    android:layout_width="fill_parent"    android:layout_height=30dip" 
    />
</LinearLayout>
like image 926
Salty Avatar asked Sep 12 '26 18:09

Salty


1 Answers

No, you are wrong. The default rounding mode is HALF_EVEN, in which case 1.25 rounds to 1.2. 1.35 would round to 1.4.

like image 114
NickT Avatar answered Sep 14 '26 06:09

NickT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!