String str(1000.1, 0);
“str” does contain decimal digits.
This is due to the internal doubleToString function treating 0 as a special value (unspecified numberOfDecimalPlaces).
Reminds me of base -909 in Python (see below), except in this case 0 decimal digits is a value that users are likely to give…
>>> int("10", 16)
>>> int("10", -908)
ValueError: int() base must be >= 2 and <= 36
>>> int("10", -909)
Hmm… Not sure I agree… I’d say that 0 decimal places is valid as a special case, because if you really don’t want any decimals, then you should really be using the integer constructor, don’t you think…?
I have just run into this myself. I would disagree with “then you should really be using the integer constructor, don’t you think”. In my case the user selects the number of decimals for a ton of parameters at run-time via the GUI. Now I have to check for 0 every time and choose the proper constructor. Not as clean as I would like I guess.
Not clean in what sense? If you mean you’ve got lots of duplicated code doing this check, then you need to D.R.Y your code, it’s not the fault of the String class!
To create and use your own convertToString() function that does exactly what you need for your own context is in many ways better coding style than making lots of direct calls to a generic library function that happens to do the “right” thing, because it encapsulates that functionality in case you need to change it later, and makes your code more clearly self-documenting.
The thing is that 0 does make sense as an input here. -1 for example doesn’t make sense and imho would make for a better “special case argument”.
Imagine if this function used 6 as the special value. Users would usually be happy but occasionally stumble on this unexpected behavior when trying to format with 6 decimal digits. After some confused debugging they would figure it out and use the easy work-around for the problem by calling formatDoubleWithMicros when they want 6 decimal digits, but there would be less confused users and less universal-DRY if the different users could use a straightforward built-in library function to do this for them.
Cheers and sry for nitpicking Yair
Ok, that’s a fair point!
TBH I’d like to revisit the double->string stuff one day anyway. I read a paper some time ago proposing a trick for stringifying numbers which would never lose any precision, and which I’d like to be able to use in things like XML conversion.
+1 here ! I have the same problem, I had to treat 0 as a special case in my code, I thought that -1 would make more sense as a “ignore the numberOfDecimalPlaces argument”
With hindsight, yes - sadly I can’t change it now without breaking people’s code…