如何在分隔符后将Decimal转换为两位数字符串?

时间:2017-10-25 13:02:12

标签: ios swift string decimal number-formatting

这就是我现在所做的:

extension Decimal {
    var formattedAmount: String {
        let formatter = NumberFormatter()
        formatter.generatesDecimalNumbers = true
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        return formatter.string(from: self) //mismatch type
    }
}

但我无法从NSNumber创建Decimal

2 个答案:

答案 0 :(得分:3)

这应该有效

#!/usr/bin/env python 
import math
import json
from time import time
t = time()

start = [1,1]
size = [600,600]

stuff = open('grid.txt','r')

world = json.loads(stuff.read())


size[0]=len(world[0])
size[1]=len(world)

goal = [600,600]

print("World size: %sx%s" % (size[0],size[1]))


def astar():

    pq = []
    pq.append(([start],0))

    print("Definitely getting here")
    hits = []

    while (pq[0][0][-1] != goal):

        currentpath = pq.pop(0)[0][:]
        hits.append(currentpath[-1])

        for n in neighbours(currentpath[-1]):
            if n in hits:
                continue

            newPath=currentpath[:]
            newPath.append(n)
            heur=len(currentpath) + heuristic(n)
            print("newPath: %s (%s)" % (newPath,heur))
            pq.append((newPath,heur))

        pq=sorted(pq, key=lambda path: path[1])

    print("Done!")

    return pq[0][0]

def neighbours(coords): # [4,5]
    x = coords[0]
    y = coords[1]
    maxx = size[0]
    maxy = size[1]
    n=[]
    for i in range (-1,2):
        for j in range(-1,2):
            if (i==0 and j==0):
                continue
            else:
                xx = x + i
                yy = y + j

                if (world[yy][xx]!=0):
                    continue

                if (xx >= 0 and yy >= 0):
                    if (xx <= maxx):
                        if (yy <= maxy):
                            n.append([xx,yy])
    return n


def heuristic(n):
    dx = abs(n[0] - goal[0])
    dy = abs(n[1] - goal[1])
    return math.sqrt(dx * dx + dy * dy) 


print(astar())

print (time() - t)

答案 1 :(得分:2)

此:

formatter.string(from: ...) // requires a NSNumber

你可以这样做:

formatter.string(for: self) // which takes Any as argument

或者:

string(from: self as NSDecimalNumber) // cast self to NSDecimalNumber