You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android计算器小数点功能异常求助:重复输入引发NaN值问题

Fixing Duplicate Decimal Points in Your Calculator App

Hey there! Let's sort out that annoying duplicate decimal point issue you're facing—totally normal for someone new to app development, so don't stress about it.

What's Causing the Problem?

Looking at your current code, the issue is that every time you tap the decimal button, you're always adding a decimal point without checking if one already exists. The try block tries to parse the current text to a double first (which works even if there's already a decimal), but then you immediately append another "."—that's why you end up with strings like "1.2." or "1..2" later on, which can't be parsed to a number (hence the NaN errors).

The Fix

We need to add simple checks before adding the decimal point. Here's how to adjust your code:

b_dot.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        String currentDisplay = show.getText().toString();
        
        // If the display is empty, start with "0." instead of just "."
        if (currentDisplay.isEmpty()) {
            show.setText("0.");
        } 
        // Only add a decimal if there isn't one already
        else if (!currentDisplay.contains(".")) {
            show.setText(currentDisplay + ".");
        }
        // Do nothing if a decimal already exists—no more duplicates!
    } 
});

Why This Works

  • Empty display check: Prevents users from entering a standalone "." (which would cause parsing errors later). Instead, we start with "0." which is a valid partial number.
  • Duplicate decimal check: Using contains(".") ensures we only add a decimal point if the current number doesn't have one already. This eliminates those invalid double-decimal strings entirely.

You can also remove that try-catch block from the decimal button click handler now—since we're preventing invalid inputs before they happen, there's no need to handle parsing exceptions here anymore.

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:05:31