尝试将dic值转换为货币值时出现问题

时间:2019-09-11 14:41:20

标签: ios swift currency nsnumber numberformatter

我有一本字典,其中Bill Price是可选的Any 我的问题是我想使用以下函数将其转换为Currency:

Encoding DefaultEncoding = Encoding.UTF8;

public IList<string[]> ReadCsvData()
{
    using (var reader = ReadBase64File())
    {
        return CsvParser.ReadCsvData(reader);
    }
}

TextReader ReadBase64File()
{
    var bytes = Convert.FromBase64String(base64File);
    return new StreamReader(new MemoryStream(bytes), DefaultEncoding, true);
}    

public static IList<string[]> ReadCsvData(TextReader reader)
{
    IList<string[]> csvData = new List<string[]>();
    using (Microsoft.VisualBasic.FileIO.TextFieldParser parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
    {
        parser.SetDelimiters(",");
        parser.TrimWhiteSpace = true;

        try
        {
            while (!parser.EndOfData)
            {
                csvData.Add(parser.ReadFields());
            }
        }
        catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex)
        {
            throw new FormatException($"Invalid format found when importing the CSV data (line {parser.ErrorLineNumber}).", ex);
        }
    }

    return csvData;
}

我使用以下数据: let currencyFormatter = NumberFormatter() currencyFormatter.usesGroupingSeparator = true currencyFormatter.numberStyle = .currency currencyFormatter.locale = Locale.current let priceString = currencyFormatter.string(from: ToConvert2) print(priceString) // Displays $9,999.99 in the US locale ->可选-某些:103.28

我尝试过:

dicType.value(forKey: "BON_PRIX")

但是我遇到致命错误,

  

在展开可选值时意外发现nil

我尝试了几件事,但没有找到正确的方法。 因此,关键是将外部服务器的数据转换为EUR,并舍入两位小数。

在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您真的不需要NSNumber

let value = dicType["BON_PRIX"] as? String
// safely convert String to Double
let roundedDoubleValue = value.flatMap { Double($0) }
// use .string(for:) instead of .string(from:)
let priceString = currencyFormatter.string(for: roundedDoubleValue }) ?? ""

答案 1 :(得分:-1)

func getEuro(strVal: String) -> String? {

   let doubleStr = Double(strVal)

   let price = doubleStr as? NSNumber

   print(price)

   let formatter = NumberFormatter()

   formatter.numberStyle = .currency

   // Changing locale to "es_ES" for Spanish Locale to get Euro currency format.

   formatter.locale = Locale(identifier: "es_ES")

   if let price = price {
      let euroPrice = formatter.string(from: price)
      print(euroPrice!) //"103,28 €"

      return euroPrice
   }

   return nil
}

print(getEuro(strVal: "103.28")) //Optional("103,28 €")