1
$\begingroup$

Some related questions include here.

Is there a way to format numbers for export in CSV or JSON as numbers - not strings - with a specified number of decimal places and no exponentials?

Is output similar to the C language printf:

printf("%3.2f\n",d);

The closest Mathematica equivalent seems to be AccountingForm but even this wraps AccountingForm head around the number and so has to be converted to string - whereas converting to expression reverts to exponentials (for larger numbers)

formatNumber[n_]:= ToString[AccountingForm[n, {15, 2}, NumberSigns -> {"-", ""}, 
   NumberPadding -> {"", "0"}]];
$\endgroup$
  • $\begingroup$ you can work with NumberForm with ExponentStep -> Infinity. Pretty much the same, but you don't need the NumberSigns option. $\endgroup$ – george2079 Apr 10 '17 at 20:14
  • $\begingroup$ @george2079, problem is, NumberForm also adds a head, so how to get around the need for ToString ? - If, instead, ToExpression gives an error as NumberForm "is not a string or box. " $\endgroup$ – alancalvitti Apr 10 '17 at 21:04
  • $\begingroup$ that's why I said pretty much the same.. more discussion here mathematica.stackexchange.com/q/970/2079 $\endgroup$ – george2079 Apr 10 '17 at 21:12
  • $\begingroup$ @george2079, thanks for the link. However, that Q is general about riffling strings, whereas my Q is more specific about formatting floating point numbers. Are you aware of implementation to handle "%3.2f" format? $\endgroup$ – alancalvitti Apr 10 '17 at 21:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.