On Tue, Mar 04, 2003 at 09:15:41AM -0700, Brad Figler wrote:
> Can someone suggest a recommended method for converting doubles to
> strings?
It's quite hard in general. The canonical reference IMHO is Steele and
White, "How to print floating-point numbers accurately", SIGPLAN '90.
That was a both Google URL and a library URL :-).
> I don't need the string in exponential format, I just need the string
> to have 1 or 2 places precision.
But, happily enough, that much is ridiculously easy.
> long iValue = ( long )1.2; // Gives me a 1.
> I then subtract out the 1, i.e 1.2 - 1.0 to get .2
> I then multiply that by 10 and get 2.0 (at least that's what the
> debugger says I have!);
> I then have the following code.
> long dValue = ( long )2.0; // Gives me a 1. <-- This is the problem
So of course what printed as 2.0 was in fact 1.999999 or so, and
truncation gave you just 1. Here is the trick:
(Pretending for now that everything is positive,) if you have a
downwards-rounding truncation function and you'd like to use it to
"round" everything in the range [1.5, 2.5) to 2, and so on, you should
do it with
(long) (x + 0.5)
I thought everyone learnt this trick in primary school? Or at home,
while programming in BASIC as a child?
John
--
For information on using the Palm Developer Forums, or to unsubscribe, please see
http://www.palmos.com/dev/support/forums/