Skip to content

Commit 2d5a67e

Browse files
committed
Quick converting to strings
1 parent 9ba70d5 commit 2d5a67e

1 file changed

Lines changed: 34 additions & 2 deletions

File tree

Sources/Math/Math.swift

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,10 +293,10 @@ public struct Math: NumberProtocol {
293293
if n < 2 { return false }
294294
if n == 2 { return true }
295295
if n % 2 == 0 { return false }
296-
296+
297297
let limit = Int(Double(n).squareRoot())
298298
if limit < 3 { return true } // no need to check further
299-
299+
300300
for i in stride(from: 3, through: limit, by: 2) {
301301
if n % i == 0 { return false }
302302
}
@@ -308,6 +308,38 @@ public struct Math: NumberProtocol {
308308
}
309309
}
310310

311+
// MARK: - String Convertible
312+
extension Math: CustomStringConvertible {
313+
public var description: String {
314+
switch storage {
315+
case .int(let v):
316+
return "\(v)"
317+
case .double(let v):
318+
return String(v) // uses default Swift formatting
319+
case .bigInt(let v):
320+
return v.description
321+
case .bigDecimal(let v, let scale):
322+
// Convert BigInt + scale → string with decimal point
323+
var s = v.description
324+
if scale == 0 { return s }
325+
326+
// Pad with leading zeros if scale > length
327+
if s.count <= scale {
328+
s = String(repeating: "0", count: scale - s.count + 1) + s
329+
}
330+
331+
let index = s.index(s.endIndex, offsetBy: -scale)
332+
s.insert(".", at: index)
333+
334+
// Strip trailing zeros
335+
while s.last == "0" { s.removeLast() }
336+
if s.last == "." { s.removeLast() }
337+
338+
return s
339+
}
340+
}
341+
}
342+
311343
// MARK: - Arithmetic Operators
312344
public extension Math {
313345
static func + (lhs: Math, rhs: Math) -> Math {

0 commit comments

Comments
 (0)