将NSString转换为货币 - 完整的故事 [英] Converting NSString to Currency - The Complete Story

查看:103
本文介绍了将NSString转换为货币 - 完整的故事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一天多的探讨这个问题后,我会看看能否得到一些帮助。这个问题之前或多或少已被提出过,但似乎没有人给出完整答案,所以希望我们现在可以得到它。

After over a day of poking around with this problem I will see if I can get some help. This question has been more or less asked before, but it seems no one is giving a full answer so hopefully we can get it now.

使用UILabel和UITextView( w /数字键盘)我想实现一个类似ATM的行为,让用户只需输入数字,并在标签中将其格式化为货币。这个想法基本上在这里概述:

Using a UILabel and a UITextView (w/ number keyboard) I want to achieve an ATM like behavior of letting the users just type the numbers and it is formatted as currency in the label. The idea is basically outlined here:

输入带小数点的数值的最佳方法是什么?

唯一的问题是它从未明确说明如何我们可以从文本字段中的123这样的整数开始,并在标签中显示为$ 1.23或123¥等。任何人都有代码执行此操作吗?

The only issue is that it never explicitly says how we can go from having an integer like 123 in the textfield and displaying in the label as $1.23 or 123¥ etc. Anyone have code that does this?

推荐答案

我找到了一个解决方案,根据这个问题的目的,我将为那些将来遇到这个问题的人提供一个完整的答案。首先,我创建了一个名为NumberFormatting的新Helper类,并创建了两个方法。

I have found a solution, and as per the purpose of this question I am going to provide a complete answer for those who have this problem in the future. First I created a new Helper Class called NumberFormatting and created two methods.

//
//  NumberFormatting.h
//  Created by Noah Hendrix on 12/26/09.
//

#import <Foundation/Foundation.h>


@interface NumberFormatting : NSObject {

}

-(NSString *)stringToCurrency:(NSString *)aString;
-(NSString *)decimalToIntString:(NSDecimalNumber *)aDecimal;

@end

这里是实施文件:

//
//  NumberFormatting.m
//  Created by Noah Hendrix on 12/26/09.
//

#import "NumberFormatting.h"


@implementation NumberFormatting

  -(NSString *)stringToCurrency:(NSString *)aString {
    NSNumberFormatter *currencyFormatter  = [[NSNumberFormatter alloc] init];
    [currencyFormatter setGeneratesDecimalNumbers:YES];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    if ([aString length] == 0)
      aString = @"0";

    //convert the integer value of the price to a decimal number i.e. 123 = 1.23
    //[currencyFormatter maximumFractionDigits] gives number of decimal places we need to have
    //multiply by -1 so the decimal moves inward
    //we are only dealing with positive values so the number is not negative
    NSDecimalNumber *value  = [NSDecimalNumber decimalNumberWithMantissa:[aString integerValue]
                                                                exponent:(-1 * [currencyFormatter maximumFractionDigits])
                                                              isNegative:NO];

    return [currencyFormatter stringFromNumber:value];
  }

  -(NSString *)decimalToIntString:(NSDecimalNumber *)aDecimal {
    NSNumberFormatter *currencyFormatter  = [[NSNumberFormatter alloc] init];
    [currencyFormatter setGeneratesDecimalNumbers:YES];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    if (aDecimal == nil)
      aDecimal = [NSDecimalNumber zero];

    NSDecimalNumber *price  = [NSDecimalNumber decimalNumberWithMantissa:[aDecimal integerValue]
                                                                exponent:([currencyFormatter maximumFractionDigits])
                                                              isNegative:NO];

    return [price stringValue];
  }

@end

第一种方法stringToCurrency,将采用整数(在本例中从文本字段传入)并使用适合用户区域设置的小数点移动将其转换为十进制值。然后它使用NSNumberFormatter返回格式化为货币的字符串表示。

The first method, stringToCurrency, will take an integer number (passed in from a textfield in this case) and convert it to a decimal value using moving the decimal point as appropriate for the users locale settings. It then returns a string representation formatted as currency using NSNumberFormatter.

第二种方法反过来采用类似1.23的值并使用类似的方法将其转换回123。

The second method does the reverse it takes a value like 1.23 and converts it back to 123 using a similar method.

这是我如何使用它的一个例子

Here is an example of how I used it

...
self.accountBalanceCell.textField.text  = [[NumberFormatting alloc] decimalToIntString:account.accountBalance];
...
[self.accountBalanceCell.textField addTarget:self
                                            action:@selector(updateBalance:)
                                  forControlEvents:UIControlEventEditingChanged];

这里我们将文本字段的值设置为数据存储中的十进制值,然后我们设置观察者观察文本字段的更改并运行方法updateBalance

Here we set the value of the text field to the decimal value from the data store and then we set a observer to watch for changes to the text field and run the method updateBalance

- (void)updateBalance:(id)sender {
  UILabel *balanceLabel = (UILabel *)[accountBalanceCell.contentView viewWithTag:1000];
  NSString *value       = ((UITextField *)sender).text;
  balanceLabel.text     = [[NumberFormatting alloc] stringToCurrency:value];
}

它只需获取textfield值并通过上述stringToCurrency方法运行它。

Which simply takes the textfield value and run it through the stringToCurrency method described above.

对我来说,这似乎是hackish所以如果你有兴趣使用它,请花点时间仔细检查并清理它。另外我注意到它的大值会破坏。

To me this seems hackish so please take the a moment to look over and clean it up if you are interested in using it. Also I notice for large values it breaks.

这篇关于将NSString转换为货币 - 完整的故事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆