Printing floats with Erlang

mochiweb,erlang

ThefloatprintingoptionsthatshipwithErlangallsuck.Youeitherdon'thavesufficientprecision,oryouhaveanextremelyverboserepresentation:

1> io:format("~w ~.18g ~g ~s~n", [0.1234567, 0.1234567, 0.1234567, float_to_list(0.1234567)]).
0.123457 0.123456700000000003 0.123457 1.23456700000000002548e-01
2> io:format("~w ~.18g ~g ~s~n", [0.1, 0.1, 0.1, float_to_list(0.1)]).
0.100000 0.100000000000000006 0.100000 1.00000000000000005551e-01

mochiwebincludesanimplementationofthealgorithmfromthe"PrintingFloating-PointNumbersQuicklyandAccurately"paperinthemochinummodule(whichisstandalone,ifyoujustwanttouseitwithouttherestofmochiweb):

3> io:format("~s~n", [mochinum:digits(0.1234567)]).
0.1234567
4> io:format("~s~n", [mochinum:digits(0.1)]).
0.1

相关推荐