OGeek|极客世界-中国程序员成长平台

标题: iphone - 实时格式化美元金额 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 08:52
标题: iphone - 实时格式化美元金额

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

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

我尝试了多种不同的方式来完成这项工作,但都存在问题。 使用 NSNumberformatter 无法正常工作。如果用户按下退格键,使用链接列表或数组将不起作用,我真的不想实现堆栈,因为我担心它会太耗时。请告知我应该如何解决这个问题。谢谢



Best Answer-推荐答案


这只是一个指示性示例,说明如何执行此操作。您应该研究此代码并根据您的情况重新调整它。试试看:

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

    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<8;i++)
    {
        // It just simulates what happens if the user types the numbers in the array.
        number= [numbers[i] floatValue] * 1.0e-2 + number*10;
        NSLog(@"%@",[formatter stringFromNumber: @(number)]);
    }
}

关于iphone - 实时格式化美元金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14966364/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4