| ... | ... | @@ -244,30 +244,46 @@ pub fn formatBuf(buf: []const u8, width: usize, |
| 244 | 244 | } |
| 245 | 245 | |
| 246 | 246 | pub fn formatFloat(value: var, context: var, output: fn(@typeOf(context), []const u8)->bool) -> bool { |
| 247 | | var buffer: [20]u8 = undefined; |
| 248 | | const float_decimal = errol3(f64(value), buffer[0..]); |
| 249 | | if (float_decimal.exp != 0) { |
| 250 | | if (!output(context, float_decimal.digits[0..1])) |
| 251 | | return false; |
| 252 | | } else { |
| 253 | | if (!output(context, "0")) |
| 247 | var x = f64(value); |
| 248 | |
| 249 | // Errol doesn't handle these special cases. |
| 250 | if (math.isNan(x)) { |
| 251 | return output(context, "NaN"); |
| 252 | } |
| 253 | if (math.isPositiveInf(x)) { |
| 254 | return output(context, "Infinity"); |
| 255 | } |
| 256 | if (math.isNegativeInf(x)) { |
| 257 | return output(context, "-Infinity"); |
| 258 | } |
| 259 | if (x == 0.0) { |
| 260 | return output(context, "0.0"); |
| 261 | } |
| 262 | if (x < 0.0) { |
| 263 | if (!output(context, "-")) |
| 254 | 264 | return false; |
| 265 | x = -x; |
| 255 | 266 | } |
| 267 | |
| 268 | var buffer: [32]u8 = undefined; |
| 269 | const float_decimal = errol3(x, buffer[0..]); |
| 270 | if (!output(context, float_decimal.digits[0..1])) |
| 271 | return false; |
| 256 | 272 | if (!output(context, ".")) |
| 257 | 273 | return false; |
| 258 | 274 | if (float_decimal.digits.len > 1) { |
| 259 | | const start = if (float_decimal.exp == 0) usize(0) else usize(1); |
| 260 | | if (!output(context, float_decimal.digits[start .. math.min(usize(7), float_decimal.digits.len)])) |
| 275 | const num_digits = if (@typeOf(value) == f32) { usize(8) } else { usize(17) }; |
| 276 | if (!output(context, float_decimal.digits[1 .. math.min(num_digits, float_decimal.digits.len)])) |
| 261 | 277 | return false; |
| 262 | 278 | } else { |
| 263 | 279 | if (!output(context, "0")) |
| 264 | 280 | return false; |
| 265 | 281 | } |
| 266 | 282 | |
| 267 | | if (float_decimal.exp != 1 and float_decimal.exp != 0) { |
| 283 | if (float_decimal.exp != 1) { |
| 268 | 284 | if (!output(context, "e")) |
| 269 | 285 | return false; |
| 270 | | if (!formatInt(float_decimal.exp, 10, false, 0, context, output)) |
| 286 | if (!formatInt(float_decimal.exp - 1, 10, false, 0, context, output)) |
| 271 | 287 | return false; |
| 272 | 288 | } |
| 273 | 289 | return true; |