Skip to content

Commit

Permalink
Fix Formatter.floatformat and Object.to_format (#1602)
Browse files Browse the repository at this point in the history
* fix: change float format specifier in Object.to_format

Fix the float format specifier in Object.to_format. If there is a float
stored in a Object such as 3.14, it would be printed out as 3 because
the format specifier is %d but should be %g.

* fix: print nan in floatformat

Fix floatformat to print 'nan' if float is nan. Currently,
io::printn(float.nan) will produce 'inf' instead of 'nan'.
  • Loading branch information
konimarti authored Nov 6, 2024
1 parent 08d1b29 commit b7a095b
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/std/collections/object.c3
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ fn usz! Object.to_format(&self, Formatter* formatter) @dynamic
case UNSIGNED_INT:
return formatter.printf("%d", (uint128)self.i)!;
case FLOAT:
return formatter.printf("%d", self.f)!;
return formatter.printf("%g", self.f)!;
case ENUM:
return formatter.printf("%d", self.i)!;
default:
Expand Down
2 changes: 1 addition & 1 deletion lib/std/io/formatter_private.c3
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ fn usz! Formatter.floatformat(&self, FloatFormatting formatting, double y) @priv
// Add padding
if (!self.flags.left) len += self.pad(' ', self.width, 3 + pl)!;
String s = self.flags.uppercase ? "INF" : "inf";
if (y != y) s = self.flags.uppercase ? "NAN" : "nan";
if (math::is_nan(y)) s = self.flags.uppercase ? "NAN" : "nan";
len += s.len;
if (pl) len += self.out(is_neg ? '-' : '+')!;
len += self.out_chars(s)!;
Expand Down

0 comments on commit b7a095b

Please sign in to comment.