0

I have the following code as the only way I know to convert a float to a string with the fewest possible significant digits required to reproduce it (dtoa() with mode 4 in C).

$i = 14;
do {
  $str = sprintf("%.{$i}e", $x);
  $i++;
} while ($x != (float) $str);

The Hack typechecker reports an error because it expects the first parameter to sprintf() to be a literal string so it can check it against the arguments. Is there a way I can turn that off for this line?

Or is there another way I could achieve the same thing? Perhaps with the NumberFormatter class?

Jesse
  • 6,725
  • 5
  • 40
  • 45

1 Answers1

1

The typechecker has various methods of suppressing errors. The most appropriate in this case is probably HH_IGNORE_ERROR to suppress this particular error.

As written, your code will produce an error like Typing[4110] Invalid argument. Take the error code, in this case "4110", and use it to add the ignore annotation:

/* HH_IGNORE_ERROR[4110] Allow dynamic sprintf() explain explain etc */
$str = sprintf("%.{$i}e", $x);

I think your error code probably is exactly 4110, but I don't have the typechecker in front of me to verify for sure, make sure to use the right code from your error message.

Note that for technical reasons the parser is pretty finicky about HH_IGNORE_ERROR -- it must be a block-style comment with no extra whitespace from what I've written above, until after the final ] at which point you can write as much as you like in the comment explaining.

Josh Watzman
  • 7,060
  • 1
  • 18
  • 26