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

浮点数输入验证:修复字符串转浮点数函数(禁用内置转换函数)

Fixing the price_to_int Function for Currency String Conversion

Your original price_to_int function has two critical issues:

  1. It directly uses float(text) which violates the requirement to avoid built-in conversion functions, and will throw an error for inputs with $ or commas (like $1,009.78).
  2. It only checks if characters are valid but doesn't actually process the formatting symbols (dollar sign, commas) or parse the number digit by digit.

Here's the corrected implementation that adheres to all your requirements—we'll process each character manually, skip valid formatting symbols, and build the numeric value without using int() or float() for string-to-number conversion:

def price_to_int(text):
    integer_part = 0
    decimal_part = 0
    decimal_places = 0
    in_decimal = False
    valid_chars = {"$", ",", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

    for char in text:
        # Reject any invalid characters immediately
        if char not in valid_chars:
            return -1

        if char == "$":
            # Skip dollar sign (handles leading $, though we don't enforce it being only leading)
            continue
        elif char == ",":
            # Skip thousands separators
            continue
        elif char == ".":
            # Only allow one decimal point
            if in_decimal:
                return -1
            in_decimal = True
        else:
            # Convert character to digit without using int()
            digit = ord(char) - ord("0")
            if not in_decimal:
                integer_part = integer_part * 10 + digit
            else:
                decimal_part = decimal_part * 10 + digit
                decimal_places += 1

    # Calculate the final value by combining integer and decimal parts
    total = integer_part
    if decimal_places > 0:
        total += decimal_part / (10 ** decimal_places)
    
    return total

How this works:

  • We track separate values for the integer and decimal parts of the number, plus how many decimal places we've processed.
  • For each character:
    • Skip valid formatting symbols ($, ,) entirely.
    • If we hit a decimal point, we flip a flag to start tracking the decimal part—if we hit a second decimal, we return -1 (invalid input).
    • For digits, we convert them to numeric values using ASCII code offsets (avoids int()), then update either the integer or decimal part accordingly.
  • Finally, we combine the integer part with the decimal part (scaled by 10^number_of_decimal_places) to get the final float value.

When you use this function with your example inputs:

  • $1,009.78 gets parsed to 1009.78 correctly
  • Goat returns -1 as expected
  • Plain values like 100.00 or 200 work as intended

This implementation strictly follows your rules: no built-in string-to-number conversions,逐字符分析 (character-by-character analysis), handles all valid formatting, and returns -1 for invalid inputs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:57