java - 为什么我的 Java 百分比略有错误?

标签 java android math

我正在 Android Studio 中编写一个简单的百分比计算器 android 应用程序。这是我的伪装:

    resultView = (TextView) findViewById(R.id.ResultView);
    percentageText = (EditText) findViewById(R.id.PercentageInput);
    numberText = (EditText) findViewById(R.id.NumberInput);

    Button calcButton = (Button) findViewById(R.id.Calculate_btn);
    calcButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view)
         {
             if(percentageText.length() != 0 && numberText.length() != 0)
             {
                 float percentage = Float.parseFloat(percentageText.getText().toString()) / 100;
                 float result = percentage * Float.parseFloat(numberText.getText().toString());
                 resultView.setText(Float.toString(result));
             }
             else if(percentageText.length() == 0 && numberText.length() == 0)
             {
                 resultView.setText("Don't be dumb...");
             }
         }
      });

所以看起来一切正常。简单的百分比总是正确的。 50%100=50, 25%50=12.5 ... 但后来我得到 3 和 6。3%10= 0.29999998 ... 不应该是 .3 吗?和 60%100= 60.000004 ... 有什么帮助吗?

最佳答案

这与 double 变量的位数有限有关。这就像说 1/3 = 0.33333333 实际上应该等于 0.33333333... 永远!

了解 Floating points and Double precision

关于java - 为什么我的 Java 百分比略有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35885031/

相关文章:

java - 将 Java SE 应用程序转换为 java web 应用程序 {netbeans}

java - Jersey URISchemeScanner

java事务不应该回滚所有记录

android - 适用于 iPhone/Android 的图像识别库/API

c# - 浮点不准确的确定性如何?

java - 计算快速排序中的比较和交换

android - 如何访问android中的BluetoothPairingDialog.java?

java - 安卓-InflateException : Binary XML file line #7

javascript - 有没有更好的方法来查询出双for循环的数据替换?

math - 仅使用校验和传输文件?