Re: Decimal rounding function
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Sat, 21 Nov 2009 17:27:49 -0800
Bubba <nickname@xxxxxxxxxxxxxxxxxxx> writes:
Greetings to all,
I'm searching for cheap, quick and easy rounding function in C, but (there
had to be but!) without any libraries. In other words, is there a sane
mathematical (or any other, for that matter) way that can be implemented
in C and round arbitrary number of decimal places them to desired decimal
places?
So, basically, something like this:
double round (double number, unsigned decimalPlaces) {
/* some magic here */ }
Basic point is to make it portable for everything from Motorola 68000 to
embedded ARM or latest gaming x64 CPU.
I tried doing it myself but couldn't even begin being puzzled about
determining number of decimal places in the first place, let alone doing
any rounding with them.
Also did some Googling research but found only solutions with strings and
similar tricks (which I was acquainted with) or written in C++. Appreciate
any help or hint.
(The name "round" is already taken.)
There's no such function in the standard, and few such functions
floating (ahem) around out there, because it's really not as useful
as you might think.
Rounding a floating-point to a specified number of decimal places is
useful only if you're producing a string representation of the number.
(Well, there might be *some* use for it, but I can't think of any.)
And if you're doing that, you might as well just produce the string
directly.
round(1.375, 1) should give you 1.4, but 1.4 cannot be represented
exactly in binary floating-point. You might get something like
1.399999999999999911182158029987476766109466552734375, which depending
on how you print it, might come out as "1.3".
What are you really trying to accomplish? What do you intended to
do with the rounded number once you've generated it? Why not just
keep it in full precision until you're ready to truncate it when
printing it or converting it to a string?
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: Decimal rounding function
- From: bartc
- Re: Decimal rounding function
- From: io_x
- Re: Decimal rounding function
- References:
- Decimal rounding function
- From: Bubba
- Decimal rounding function
- Prev by Date: Re: function returning pointer
- Next by Date: Re: function returning pointer
- Previous by thread: Re: Decimal rounding function
- Next by thread: Re: Decimal rounding function
- Index(es):
Relevant Pages
|