Number formatting

This commit is contained in:
cdricms
2025-08-07 16:03:47 +02:00
parent 04e343b091
commit 9f08712ae7

View File

@@ -275,19 +275,22 @@ public struct UnitValue<ValueType: ConvertibleToDouble>:
}
// New reusable function
public func formatted(maximumFractionDigits: Int) -> String {
public func formatted(maximumFractionDigits: Int, showUnit: Bool = true)
-> String
{
let formatter = NumberFormatter()
formatter.maximumFractionDigits = maximumFractionDigits
formatter.minimumFractionDigits = 0 // To avoid trailing zeros when not needed
formatter.numberStyle = .decimal
if let formattedValue = formatter.string(
from: NSNumber(value: self.value))
from: NSNumber(value: value))
{
return "\(formattedValue) \(self.unit.rawValue)"
} else {
return "\(self.value) \(self.unit.rawValue)"
return showUnit
? "\(formattedValue) \(unit.rawValue)" : "\(formattedValue)"
}
return showUnit ? "\(value) \(unit.rawValue)" : "\(value)"
}
// MARK: Equatable & Comparable Conformance