Skip to content

Commit 682c771

Browse files
committed
fix: balance overflow
1 parent dc057ad commit 682c771

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
@@ -38,22 +38,28 @@ extension UInt64 {
3838
if self == 0 {
3939
return "0.00 000 000"
4040
} else {
41-
let balanceString = String(format: "%010d", self)
42-
43-
let zero = balanceString.prefix(2)
44-
let first = balanceString.dropFirst(2).prefix(2)
45-
let second = balanceString.dropFirst(4).prefix(3)
46-
let third = balanceString.dropFirst(7).prefix(3)
47-
48-
var formattedZero = zero
49-
50-
if zero == "00" {
51-
formattedZero = zero.dropFirst()
52-
} else if zero.hasPrefix("0") {
53-
formattedZero = zero.suffix(1)
54-
}
55-
56-
let formattedBalance = "\(formattedZero).\(first) \(second) \(third)"
41+
// Convert satoshis to BTC (1 BTC = 100,000,000 sats)
42+
let btcValue = Double(self) / 100_000_000.0
43+
44+
// Format BTC value to exactly 8 decimal places
45+
let btcString = String(format: "%.8f", btcValue)
46+
47+
// Split the string at the decimal point
48+
let parts = btcString.split(separator: ".")
49+
guard parts.count == 2 else { return btcString }
50+
51+
let wholePart = String(parts[0])
52+
let decimalPart = String(parts[1])
53+
54+
// Ensure decimal part is exactly 8 digits
55+
let paddedDecimal = decimalPart.padding(toLength: 8, withPad: "0", startingAt: 0)
56+
57+
// Format as XX.XX XXX XXX
58+
let first = paddedDecimal.prefix(2)
59+
let second = paddedDecimal.dropFirst(2).prefix(3)
60+
let third = paddedDecimal.dropFirst(5).prefix(3)
61+
62+
let formattedBalance = "\(wholePart).\(first) \(second) \(third)"
5763

5864
return formattedBalance
5965
}

0 commit comments

Comments
 (0)