How do you convert the double 15.350000000000001 automatically to a string "13.35" without having to specify the number of decimal places?
I know that there is double.toStringAsFixed but it has the huge drawback that it converts 1 to "1.00" which is not what I want.
I’m looking for a function which can pretty-print every double with automatic decimal places detection.
2
Answers
You could convert it to String and then do some logic / iteration through the decimals to determine the index when you should accept it and then use
toStringAsFixed
or you could use a Regexp to find and acceptable match:The pattern:
I use
00
as the end because sometimes you could find acceptable things like 4.090000001 so it can retrieve 4.09, but you can investigate more of what is your need and change to accept the first zero after a . if there is a number after that, is up to youMy solution (FormatFloat from Delphi) using intl package:
Using: