Anybody know a quick and dirty function for going from "547.6458679" to
the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){
int intNum;
//Do some stuff...
return intNum;
}
I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks, 13 2518
ern wrote: Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
#include <stdlib.h>
#include <math.h>
int returnIntegerEquivalent(char * charNum){ int intNum;
double dNum = strtod(charNum, NULL);
if (ceil(dNum) - dNum > 0.5)
intNum = (int) floor(dNum);
else
intNum = (int) ceil(dNum);
return intNum; }
I was using the Windows stuff before (ie _gcvt() and atof()). Thanks,
ern wrote: Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){ int intNum; //Do some stuff...
intNum = atof(charNum) + 0.5;
return intNum; }
I was using the Windows stuff before (ie _gcvt() and atof()). Thanks,
"ern" <er*******@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com... Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
rounding to +infinity is done with ceil()
examples:
547.6 -> 548
547.4 -> 548
547 -> 547
-547.4 -> -547
-547.6 -> -547
rounding to -infinity is done with floor()
examples:
547.6 -> 547
547.4 -> 547
547 -> 547
-547.4 -> -548
-547.6 -> -548
truncating the fractional part is done by converting/casting to integer
type:
547.6 -> 547
547.4 -> 547
547 -> 547
-547.4 -> -547
-547.6 -> -547
rounding to the nearest integer can be achieved from truncating if 0.5 is
first [added to]/[subtracted from] the number being rounded:
547.6+0.5 -> 548
547.4+0.5 -> 547
547+0.5 -> 547
-547.4-0.5 -> -547
-547.6-0.5 -> -548
Something like that,
Alex
"ern" <er*******@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com... Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){ int intNum; //Do some stuff... return intNum; }
I was using the Windows stuff before (ie _gcvt() and atof()). Thanks,
I'm not sure how "dirty" (or quick, for that matter) it is, but you'll
probably want to look into the strtol() function: http://ccs.ucsd.edu/c/stdlib.html#strtol. More intuitively, you could
convert the string to a (double) using the related strtod() function
( http://ccs.ucsd.edu/c/stdlib.html#strtod), and then cast the result to an
(int), especially since you have to do that anyway with strtol() unless you
declare "intNUM" of type (long).
-Charles
ern wrote: Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){ int intNum; //Do some stuff... return intNum; }
I was using the Windows stuff before (ie _gcvt() and atof()). Thanks,
#include <errno.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
/* making no assumption that s represents an value in the range of an
int, but accepting that some initial portion is supposed to represent
a legal double value. 0 is returned (with errno set) if a problem occurs
with the string to float conversion. */
double floatingstring2floatingint(const char *s)
{
double x, fp, ip;
int sign = 1;
errno = 0;
x = strtod(s, 0);
if (errno)
return 0;
if (x < 0) {
sign = -1;
x = -x;
}
fp = modf(x, &ip);
if (fp >= .5)
ip++;
return sign * ip;
}
int main(void)
{
char s[] = "547.6458679";
char t[] = "-547.6458679";
printf("The initial string (s) is \"%s\n", s);
printf("floatingstring2floatingint(s) returns %g\n",
floatingstring2floatingint(s));
printf("The initial string (t) is \"%s\n", t);
printf("floatingstring2floatingint(t) returns %g\n",
floatingstring2floatingint(t));
return 0;
}
The initial string (s) is "547.6458679
floatingstring2floatingint(s) returns 548
The initial string (t) is "-547.6458679
floatingstring2floatingint(t) returns -548
"Charles M. Reinke" <cm******@ece.gatech.edu> wrote in message
news:dh**********@news-int.gatech.edu... "ern" <er*******@gmail.com> wrote in message news:11*********************@g14g2000cwa.googlegro ups.com... Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){ int intNum; //Do some stuff... return intNum; }
I was using the Windows stuff before (ie _gcvt() and atof()). Thanks,
I'm not sure how "dirty" (or quick, for that matter) it is, but you'll probably want to look into the strtol() function: http://ccs.ucsd.edu/c/stdlib.html#strtol. More intuitively, you could convert the string to a (double) using the related strtod() function (http://ccs.ucsd.edu/c/stdlib.html#strtod), and then cast the result to an (int), especially since you have to do that anyway with strtol() unless
you declare "intNUM" of type (long).
-Charles
After sending my inital response I realized that the proper solution could
be a little complicated, hence the following code:
holomask>cat h.c
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int returnIntegerEquivalent(char *charNum) {
int intNum;
char *str_test;
intNum = floor(strtod(charNum, &str_test)+0.5);
if(charNum==str_test)
printf("Error converting string.\n");
return intNum;
} /* returnIntegerEquivalent */
int main(void) {
int intNum;
char charNum[]="547.6458679";
intNum = returnIntegerEquivalent(charNum);
printf("test string: %s\ninteger value: %d\n", charNum, intNum);
return 0;
} /* main */
holomask>gcc -Wall -ansi -pedantic -lm -o h.exe h.c
holomask>h.exe
test string: 547.6458679
integer value: 548
"Charles M. Reinke" <cm******@ece.gatech.edu> wrote in
news:dh**********@news-int.gatech.edu: intNum = floor(strtod(charNum, &str_test)+0.5); if(charNum==str_test) printf("Error converting string.\n");
In cases like this, it might be more useful to test that the string
contained nothing other than a valid number. For example, the test above
would not raise an error if
"547.64.58679"
was passed to it.
Thus, a test like
if( *str_test ) {
/* error */
}
might be more useful in practice.
Sinan
--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)
"A. Sinan Unur" <1u**@llenroc.ude.invalid> wrote in message
news:Xn****************************@127.0.0.1... In cases like this, it might be more useful to test that the string contained nothing other than a valid number. For example, the test above would not raise an error if
"547.64.58679"
was passed to it.
Agreed.
Thus, a test like
if( *str_test ) { /* error */ }
might be more useful in practice.
Sinan
Point well taken. ;-)
-Charles
"Charles M. Reinke" <cm******@ece.gatech.edu> wrote in
news:dh**********@news-int.gatech.edu: "A. Sinan Unur" <1u**@llenroc.ude.invalid> wrote in message news:Xn****************************@127.0.0.1... In cases like this, it might be more useful to test that the string contained nothing other than a valid number. For example, the test above would not raise an error if
"547.64.58679"
was passed to it. Agreed.
Thus, a test like
if( *str_test ) { /* error */ }
might be more useful in practice.
.... Point well taken. ;-)
I should note that this requires str_test to be initialized.
char *str_test = charNum;
should be good enough.
--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)
comp.lang.perl.misc guidelines on the WWW: http://mail.augustmail.com/~tadmc/cl...uidelines.html
Yep. That's the quick and dirty method.
What I find interesting is that in none of the other examples in this thread
to they address the additional rounding rules if the value is .5 - as in
"547.500". As I recall, round up on even, down on odd.
--
---------------------------------------------------------------------
DataGet & PocketLog www.dataget.com
Data Collectors www.baxcode.com
--------------------------------------------------------------------
"tedu" <tu@zeitbombe.org> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com... ern wrote: Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){ int intNum; //Do some stuff...
intNum = atof(charNum) + 0.5;
return intNum; }
I was using the Windows stuff before (ie _gcvt() and atof()). Thanks,
On 27 Sep 2005 13:42:54 -0700, "tedu" <tu@zeitbombe.org> wrote in
comp.lang.c: ern wrote: Anybody know a quick and dirty function for going from "547.6458679" to the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){ int intNum; //Do some stuff...
intNum = atof(charNum) + 0.5;
No, very bad! Seriously undefined behavior possible, for two reasons. return intNum;
First the ato... functions are all old hacks that should never be
used. They produce undefined behavior if the converted result is
outside the range of the destination type. That's why the C standard
added the strto... functions that have defined behavior with any input
other than a null pointer.
Second, even if the value doesn't overflow and atof() returns a valid
double, the integer part of that double might be outside the range
that can be represented in a signed int. Boom, undefined behavior.
Finally there is the minor point that this does 5/4 rounding to a
greater magnitude for positive numbers but to a lesser magnitude for
negative ones.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
"Baxter" <lb**************@baxcode.com> wrote in message
news:11*************@corp.supernews.com... What I find interesting is that in none of the other examples in this
thread to they address the additional rounding rules if the value is .5 - as in "547.500". As I recall, round up on even, down on odd.
Not many know or simply remember (if ever learned) this Gauss
correction-on-rounding rule.
The rule is to round a number having the fractional equal to 0.5 to the
nearest even integer.
Examples:
2.5 -> 2 (not 3)
3.5 -> 4
-3.5 -> -4
-2.5 -> -2 (not -3)
It's perfectly OK to change this to the opposite (rount to the nearest odd
integer):
2.5 -> 3
3.5 -> 3 (not 4)
-3.5 -> -3 (not -4)
-2.5 -> -3
The absolute value of the rounding error is the same in both cases (0.5),
but if this additional correction is enforced, rounding errors of such
numbers tend to compensate each other on summation/subtraction.
Alex
On Wed, 28 Sep 2005 10:38:59 +0400, Alexei A. Frounze wrote:
[...] [T]his Gauss correction-on-rounding rule... is to round a number having the fractional equal to 0.5 to the nearest even integer. [R]ounding errors of such numbers tend to compensate each other on summation/subtraction.
Beauty in effective simplicity.
-- http://members.dodo.com.au/~netocrat This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Christopher Benson-Manica |
last post by:
I need a smart char * class, that acts like a char * in all cases, but
lets you do some std::string-type stuff with it. (Please don't say to
use std::string - it's not an option...). This is my...
|
by: Alex Vinokur |
last post by:
"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c
> ben19777@hotmail.com (Ben) wrote:
> > 2) Structure casted into an...
|
by: Sona |
last post by:
I understand the problem I'm having but am not sure how to fix it. My
code passes two char* to a function which reads in some strings from a
file and copies the contents into the two char*s. Now...
|
by: Peter Nilsson |
last post by:
In a post regarding toupper(), Richard Heathfield once asked me to think
about what the conversion of a char to unsigned char would mean, and whether
it was sensible to actually do so. And pete has...
|
by: jab3 |
last post by:
(again :))
Hello everyone.
I'll ask this even at risk of being accused of not researching adequately.
My question (before longer reasoning) is: How does declaring (or defining,
whatever) a...
|
by: GRoll35 |
last post by:
I get 4 of those errors. in the same spot. I'll show my parent class,
child class, and my driver.
All that is suppose to happen is the user enters data and it uses
parent/child class to display...
|
by: Pedro Pinto |
last post by:
Hi there once more........
Instead of showing all the code my problem is simple.
I've tried to create this function:
char temp(char *string){
alterString(string);
return string;
|
by: Paul Brettschneider |
last post by:
Hello all,
consider the following code:
typedef char T;
class test {
T *data;
public:
void f(T, T, T);
void f2(T, T, T);
|
by: s0suk3 |
last post by:
This code
#include <stdio.h>
int main(void)
{
int hello = {'h', 'e', 'l', 'l', 'o'};
char *p = (void *) hello;
for (size_t i = 0; i < sizeof(hello); ++i) {
|
by: Kenzogio |
last post by:
Hi,
I have a struct "allmsg" and him member :
unsigned char card_number; //16
allmsg.card_number
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
| |