Skip to content

Commit 9cd0612

Browse files
authored
fix: balance overflow
1 parent 6dd3156 commit 9cd0612

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

BDKSwiftExampleWallet/Extensions/Int+Extensions.swift

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -48,22 +48,28 @@ extension UInt64 {
4848
if self == 0 {
4949
return "0.00 000 000"
5050
} else {
51-
let balanceString = String(format: "%010d", self)
52-
53-
let zero = balanceString.prefix(2)
54-
let first = balanceString.dropFirst(2).prefix(2)
55-
let second = balanceString.dropFirst(4).prefix(3)
56-
let third = balanceString.dropFirst(7).prefix(3)
57-
58-
var formattedZero = zero
59-
60-
if zero == "00" {
61-
formattedZero = zero.dropFirst()
62-
} else if zero.hasPrefix("0") {
63-
formattedZero = zero.suffix(1)
64-
}
65-
66-
let formattedBalance = "\(formattedZero).\(first) \(second) \(third)"
51+
// Convert satoshis to BTC (1 BTC = 100,000,000 sats)
52+
let btcValue = Double(self) / 100_000_000.0
53+
54+
// Format BTC value to exactly 8 decimal places
55+
let btcString = String(format: "%.8f", btcValue)
56+
57+
// Split the string at the decimal point
58+
let parts = btcString.split(separator: ".")
59+
guard parts.count == 2 else { return btcString }
60+
61+
let wholePart = String(parts[0])
62+
let decimalPart = String(parts[1])
63+
64+
// Ensure decimal part is exactly 8 digits
65+
let paddedDecimal = decimalPart.padding(toLength: 8, withPad: "0", startingAt: 0)
66+
67+
// Format as XX.XX XXX XXX
68+
let first = paddedDecimal.prefix(2)
69+
let second = paddedDecimal.dropFirst(2).prefix(3)
70+
let third = paddedDecimal.dropFirst(5).prefix(3)
71+
72+
let formattedBalance = "\(wholePart).\(first) \(second) \(third)"
6773

6874
return formattedBalance
6975
}

0 commit comments

Comments
 (0)