Skip to content

Instantly share code, notes, and snippets.

@kk-vv
Created November 3, 2023 10:48
Show Gist options
  • Save kk-vv/240052cbdf814bcfcf37fcefd31fb7ab to your computer and use it in GitHub Desktop.
Save kk-vv/240052cbdf814bcfcf37fcefd31fb7ab to your computer and use it in GitHub Desktop.
BigInt to string
import Foundation
import BigInt
extension BigUInt {
func string(decimals: Int) -> String {
"\(self)".bigIntToString(decimals: decimals)
}
}
extension BigInt {
func bigIntToString(decimals: Int) -> String {
"\(self)".bigIntToString(decimals: decimals)
}
}
extension String {
func bigIntToString(decimals: Int) -> String {
var amount = self.components(separatedBy: ".").first ?? "0"
if self == "0" || decimals == 0 {
return amount
}
let dt = (decimals + 1) - amount.count
if dt > 0 {
for _ in 0..<dt {
amount.insert("0", at: amount.startIndex)
}
}
var offset = amount.count - decimals
if offset == 0 {
offset = 1
}
let left = amount[0..<offset]
let right = amount[offset..<offset + min(amount.count - left.count, 6)]
let formattedAmount = left + "." + right
return formattedAmount.trimmingZeroDecimal
}
func bigInt(decimals: Int) -> BigInt {
guard decimals >= 0 else {
return 0
}
var numbers = self.components(separatedBy: ".")
if numbers.count == 1 {
var number = numbers[0]
number += String(repeating: "0", count: decimals)
return BigInt(stringLiteral: number)
} else if numbers.count == 2 {
var head = numbers[0]
var tail = numbers[1]
if tail.count > decimals {
tail = tail[0..<decimals]
let number = head + tail
return BigInt(stringLiteral: number)
} else {
let offset = decimals - tail.count
var number = head + tail
number += String(repeating: "0", count: offset)
return BigInt(stringLiteral: number)
}
}
return 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment