如何在RubyMotion中使用NSDecimalNumber类方法?

时间:2014-05-09 01:33:20

标签: ios rubymotion nsdecimalnumber

我试图将Objective-C中的这些代码行转换为RubyMotion,但它无法正常工作。

 NSDecimalNumber *subtotal = [[NSDecimalNumber alloc] initWithString:@"12.34"];

  NSDecimalNumber *shipping = [[NSDecimalNumber alloc] initWithString:@"5.99"];

  NSDecimalNumber *tax = [[NSDecimalNumber alloc] initWithString:@"2.50"];

  NSDecimalNumber *total = [[subtotal decimalNumberByAdding:shipping] decimalNumberByAdding:tax];

这是我尝试使用RubyMotion,但它不起作用:

subtotal = NSDecimalNumber.decimalNumberWithString('12.34')

shipping = NSDecimalNumber.decimalNumberWithString('5.99')

tax = NSDecimalNumber.decimalNumberWithString('2.50') 

total = (subtotal.decimalNumberByAdding(shipping)).decimalNumberByAdding(tax)

这是我得到的错误:

未定义的方法`decimalNumberByAdding' for 12.3400001525879:Float(NoMethodError)

关于我做错什么的任何想法?

2 个答案:

答案 0 :(得分:2)

你应该能够做到这一点:

subtotal = "12.34".to_f
shipping = "5.99".to_f
tax = "2.50".to_f

total = subtotal + shipping + tax

请注意这些奇怪的转换。也许#round(2)可以提供帮助。

(main)> subtotal = "12.34".to_f
=> 12.3400001525879
(main)> shipping = "5.99".to_f
=> 5.98999977111816
(main)> tax = "2.50".to_f
=> 2.5
(main)> total = subtotal + shipping + tax
=> 20.8299942016602

正如matthewsinclair所建议的那样,最佳做法是使用整数并将所有内容存储为分数。这样你就不会遇到任何这些转换问题。

答案 1 :(得分:2)