【问题标题】:How do append two decimal point after the amount如何在金额后附加两位小数
【发布时间】:2017-04-18 12:52:57
【问题描述】:

我尝试使用以下值将两个小数点转换为小数样式。请参考下面的示例。

    --->1 expected 1.00
    --->1. expected 1.00
    ---->1.0 expected 1.00
    --->1.01 expected 1.01
    --->1235.06 expected 1,235.06
    --->12356.36 expected 12,356.36 
   ---->12356.0 expected 12,356.00
   --->12356. expected 12356.00

我尝试下面的代码,但它对我不起作用。请帮助我。

   NSNumberFormatter *doubleValueWithMaxTwoDecimalPlaces = [[NSNumberFormatter alloc] init];

    [doubleValueWithMaxTwoDecimalPlaces setNumberStyle:NSNumberFormatterDecimalStyle];

    [doubleValueWithMaxTwoDecimalPlaces setPaddingPosition:NSNumberFormatterPadAfterSuffix];

    [doubleValueWithMaxTwoDecimalPlaces setFormatWidth:2];

    [doubleValueWithMaxTwoDecimalPlaces setMaximumFractionDigits:2];

    doubleValueWithMaxTwoDecimalPlaces.positiveFormat = @"0.##";

    NSNumber *myValue = [NSNumber numberWithDouble:1.01];

    NSNumber *myValue1 = [NSNumber numberWithDouble:1.0];

    NSNumber *myValue2 = [NSNumber numberWithDouble:1.];

    NSNumber *myValue3 = [NSNumber numberWithDouble:1];

    NSLog(@" [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue] :%@", [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue]);

    NSLog(@" [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue] :%@", [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue1]);

    NSLog(@" [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue] :%@", [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue2]);

    NSLog(@" [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue] :%@", [doubleValueWithMaxTwoDecimalPlaces stringFromNumber:myValue3]);

【问题讨论】:

    标签: objective-c nsnumberformatter


    【解决方案1】:
     self.discountPriceLabel.text = [NSString stringWithFormat:@"Rs %.2f",_productDetails.discountprice];
    

    【讨论】:

      【解决方案2】:

      要修复小数位数,您需要设置 最小 小数位数以及您所做的最大值 - 在您的情况下将它们都设置为 2。您还需要设置使用千位分隔符的属性,因为这不是NSNumberFormatterDecimalStyle 的默认值。使用属性样式设置编写的以下内容应该会产生您想要的结果:

      doubleValueWithMaxTwoDecimalPlaces.numberStyle = NSNumberFormatterDecimalStyle;
      doubleValueWithMaxTwoDecimalPlaces.maximumFractionDigits = 2;
      doubleValueWithMaxTwoDecimalPlaces.minimumFractionDigits = 2;
      doubleValueWithMaxTwoDecimalPlaces.hasThousandSeparators = YES;
      

      (使用的千位分隔符将是适合当前语言环境的分隔符,如果您总是需要逗号,您也应该设置它。)

      HTH

      【讨论】:

        猜你喜欢
        • 2022-07-12
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2011-12-23
        • 2017-03-02
        • 1970-01-01
        • 2016-06-24
        • 1970-01-01
        相关资源
        最近更新 更多