菜鸟教程小白 发表于 2022-12-12 08:52:33

iphone - 实时格式化美元金额


                                            <p><p>我正在开发一个要求用户输入美元金额的 iOS 应用。它需要允许他们输入最大值为 $9999.99 的美元和美分</p>

<p>我希望它像这样工作:
有一个文本字段显示:“$ 0.00”
输入 $5.25 输入将随着每次按键而改变。
所以它看起来像这样:
'5'被按下,显示:$0.05
'2' 被按下,显示:$0.52
'5'被按下,显示:$5.25</p>

<p>我尝试了多种不同的方式来完成这项工作,但都存在问题。
使用 NSNumberformatter 无法正常工作。如果用户按下退格键,使用链接列表或数组将不起作用,我真的不想实现堆栈,因为我担心它会太耗时。请告知我应该如何解决这个问题。谢谢</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这只是一个指示性示例,说明如何执行此操作。您应该研究此代码并根据您的情况重新调整它。试试看:</p>

<pre><code>@autoreleasepool
{
    // Here I create the formatter and I set the format. You do this faster with setFormat: .
    NSNumberFormatter* formatter=[init];
    formatter.numberStyle= NSNumberFormatterCurrencyStyle;
    formatter.maximumIntegerDigits=6;
    formatter.maximumFractionDigits=2;
    formatter.currencySymbol= @&#34;$&#34;;
    formatter.currencyDecimalSeparator= @&#34;.&#34;;
    formatter.currencyGroupingSeparator= @&#34;,&#34;;
    formatter.positivePrefix=@&#34;&#34;;

    NSArray* numbers= @[ @1 ,@2 ,@3 ,@4, @5, @6, @7, @8];
    // These are the inserted numbers, you should change the code in a way that
    // every number is taken in input from the text field.
    float number=0.0f;
    for(NSUInteger i=0;i&lt;8;i++)
    {
      // It just simulates what happens if the user types the numbers in the array.
      number= floatValue] * 1.0e-2 + number*10;
      NSLog(@&#34;%@&#34;,);
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于iphone - 实时格式化美元金额,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/14966364/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/14966364/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iphone - 实时格式化美元金额