Today I found printing Double or Float from embedded swift on ESP32 is kinda impossible: undefined reference to 'swift_float32ToString'
. I even start to ask ChatGuPoT, but he had some hallucination, or I could not understand him.
I made something like this:
extension BinaryFloatingPoint {
func string(_ decimal: Int) -> String { // -1234,5678
let isNeg = self < 0
var val = abs(self) // 1234,5678
var round = val.rounded(.down) // 1234.0
var rest = val - round // 0.5678
var result = "\(isNeg ? "-" : "")\(Int(val))." // "-1234."
for _ in 0..<decimal {
val = rest * 10 // 5.678
round = val.rounded(.down) // 5.0
rest = val - round // 0.678
result = "\(result)\(Int(round))" // "1234.5"
}
return result
}
}
works.
You should be able to get close to what you would expect from "normal" Swift by adding something like this
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: Double) {
self.appendLiteral(value.description) // or your value.string(x) implementation
}
}
extension Double {
var description: String {
// add Double to String logic here
}
}
That should make print("value: \(double))"
work as expected.
Depending on your embedded setup you might offload the value to string conversion to the C standard library. I am using snprintf
for that through a C wrapper to get around the CVarArg not supported issue.