473,785 Members | 2,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to get number of digits in int variable?

Hello,

I'm trying to write a printf statement that sets the field width when
printing a number. I'm using this:

printf("%*", fieldwidth, num_to_print);

However, I can't figure out how to get the number of digits in the
number (which I would then assign to the 'fieldwidth' variable above).

I know I don't have to explicitly set the field width with printf, but
I would like very much to know how to discover it.

Can anyone suggest how I might get the number of digits for a numeric
variable?

Thanks...

Nov 14 '05 #1
10 4244
gu*****@gmail.c om wrote:
Hello,

I'm trying to write a printf statement that sets the field width when
printing a number. I'm using this:

printf("%*", fieldwidth, num_to_print);
Which will not do anything useful.
ITYM "%*d" or whatever format specifier is appropriate for
num_to_print.
However, I can't figure out how to get the number of digits in the
number (which I would then assign to the 'fieldwidth' variable above).
If num_to_print is of type int, you could use
int tmp = num_print;

for (fieldwidth = 0; tmp != 0; tmp /= 10)
fieldwidth += 1;
if (num_print < 0)
fieldwidth += 1;
(untested)
Otherwise you want
fieldwidth = (int)ceil(log(f abs(num_print))/log(10)) + (num_print < 0);
which is quite a lot of work for this information.
Alternatively, I would just use 1 + (CHAR_BIT*sizeo f num_print)/3
as an overestimation to get an always wide enough field.

I know I don't have to explicitly set the field width with printf, but
I would like very much to know how to discover it.

Can anyone suggest how I might get the number of digits for a numeric
variable?


Note that the above is about integer types.
Floating point types
- tell you how many (valid) decimal digits they have
- and usually should not printed to their full precision
if not necessary

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
Michael Mair wrote:
gu*****@gmail.c om wrote:
Hello,

I'm trying to write a printf statement that sets the field width when
printing a number. I'm using this:

printf("%*", fieldwidth, num_to_print);

Which will not do anything useful.
ITYM "%*d" or whatever format specifier is appropriate for
num_to_print.
However, I can't figure out how to get the number of digits in the
number (which I would then assign to the 'fieldwidth' variable above).

If num_to_print is of type int, you could use
int tmp = num_print;

for (fieldwidth = 0; tmp != 0; tmp /= 10)
fieldwidth += 1;
if (num_print < 0)
fieldwidth += 1;
(untested)
Otherwise you want
fieldwidth = (int)ceil(log(f abs(num_print))/log(10)) + (num_print < 0);
which is quite a lot of work for this information.
Alternatively, I would just use 1 + (CHAR_BIT*sizeo f num_print)/3
as an overestimation to get an always wide enough field.

I know I don't have to explicitly set the field width with printf, but
I would like very much to know how to discover it.

Can anyone suggest how I might get the number of digits for a numeric
variable?

Note that the above is about integer types.
Floating point types
- tell you how many (valid) decimal digits they have
- and usually should not printed to their full precision
if not necessary

Cheers
Michael

Wouldn't that be quite slow? Why not bitshift an int of value 1?
Nov 14 '05 #3
gu*****@gmail.c om wrote:
# Hello,
#
# I'm trying to write a printf statement that sets the field width when
# printing a number. I'm using this:
#
# printf("%*", fieldwidth, num_to_print);
#
# However, I can't figure out how to get the number of digits in the
# number (which I would then assign to the 'fieldwidth' variable above).

L = entier(log10(|n |))+1, |n|>=1, is the number of digits left of the decimal point.
For -1<n<1, it is customary to present L=1 digit ('0') left of the decimal point.
If n<0, it is customary to include a negative mark such as '-'.

All reals have an infinite repeating or nonrepeating decimal representation,
so that right of the decimal point there's no specific limit. For integers, you
can use 0. For floats, if you can get the approximate number of significant
digits supported by the hardware, S, you can use R = S-L as the number of digits
to the right for |n|>=1. For |n|<1, n!=0, you can use entier(-log10(|n|))
zero digits followed by S significant digits.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
If you plan to shoplift, let us know.
Thanks
Nov 14 '05 #4
On Thu, 19 May 2005 06:46:07 +0200, Michael Mair
<Mi**********@i nvalid.invalid> wrote:
If num_to_print is of type int, you could use
int tmp = num_print;

for (fieldwidth = 0; tmp != 0; tmp /= 10)
fieldwidth += 1;
if (num_print < 0)
fieldwidth += 1;
(untested)


Then test it with tmp = 0 :-)

A multiplication would be faster than a division and doesn't really
change the readability of the code (shifts would and multiplications
are so fast nowadays that it doesn't really pay to use them instead of
mulitplications when more than 1 shift is needed).

int tmp = num_print, fieldwidth = 1, testvalue = 10;

if (tmp < 0)
{
++ fieldwidth;
tmp *= -1;
}
if (tmp > SomeOverflowVal ue)
fieldwidth += TheNumberOfDigi tsOfThatOverflo wValueMinus1
else
while(tmp >= testvalue)
{
++ fieldwidth;
testvalue *= 10;
}

For a 32 bit integer "SomeOverflowVa lue" would be 1 billion (we don't
want undefined behaviour which would probably result in an endless
loop).

Of course, a far quicker solution would involve a lot of if's.
Something like this (you'll need to know the maximum value an int can
have as defined in limits.h) :

if (tmp < 10000)
if (tmp < 100)
if (tmp < 10)
fieldwidth += 1;
else
fieldwidth += 2;
else if (tmp < 1000)
fieldwidth += 3;
else
fieldwidth += 4;
else if (tmp < 10000000)

etc.

The basic idea is that the number of executed if's will be minimized
by using some binary tree like structure (checking first for the
situation with half the maximum number of digits, etc.).

I'm sure there must be better ways but, unfortunately, I'm not
mathematically endowed :-)

Nov 14 '05 #5
gu*****@gmail.c om wrote:

I'm trying to write a printf statement that sets the field width
when printing a number. I'm using this:

printf("%*", fieldwidth, num_to_print);

However, I can't figure out how to get the number of digits in
the number (which I would then assign to the 'fieldwidth' variable
above).

I know I don't have to explicitly set the field width with
printf, but I would like very much to know how to discover it.

Can anyone suggest how I might get the number of digits for a
numeric variable?


The following routine may be useful. They have been designed to
avoid the heavy overhead of a complete printf system.
/* Mask and convert digit to hex representation */
/* Output range is 0..9 and a..f only */
static int hexify(unsigned int value)
{
static char hexchars[] = "0123456789abcd ef";

return (hexchars[value & 0xf]);
} /* hexify */

/* ----------------------- */

/* Convert value to stream of digits
A NULL value for f returns a char count with no output
Returns count of chars. output
return is negative for any output error */
int unum2txt(unsign ed long n, int base, FILE *f)
{
int count, err;

if ((base < 2) || (base > 16)) base = 10;
count = 1;
if (n / base) {
if ((err = unum2txt(n / base, base, f)) < 0) return err;
else count += err;
}
if (f && (putc(hexify(n % base), f) < 0)) return -count;
return count;
} /* unum2txt */

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #6

<gu*****@gmail. com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Hello,
I'm trying to write a printf statement that sets the field width when
printing a number. I'm using this:
printf("%*", fieldwidth, num_to_print); format specification is missing type...
However, I can't figure out how to get the number of digits in the
number (which I would then assign to the 'fieldwidth' variable above).
I know I don't have to explicitly set the field width with printf, but
I would like very much to know how to discover it.
Can anyone suggest how I might get the number of digits for a numeric
variable?


sprintf();
....
char szbuf[40];
fieldwidth = sprintf(szbuf, "%d", num_to_print);

Mark
Nov 14 '05 #7
Mark wrote:
<gu*****@gmail. com> wrote:
I can't figure out how to get the number of digits in the number
Can anyone suggest how I might get the number of digits for a numeric variable?


sprintf();
...
char szbuf[40];
fieldwidth = sprintf(szbuf, "%d", num_to_print);


I'm getting slightly pedantic here, but on a system with 128-bit int
(or larger), this may cause a buffer overflow.
You could either use the preprocessor to determine the maximum
buffer size required, or if using C99, snprintf(0, 0, "%d", num).

Nov 14 '05 #8
Hi folks,

Thanks muchly for your ideas. Mark's idea of using sprintf seems a good
one, so I'll try that. Old Wolf, thanks for the note about buffer
overflows too...

G.

Nov 14 '05 #9
gu*****@gmail.c om wrote:
Hello,

I'm trying to write a printf statement that sets the field width when
printing a number. I'm using this:

printf("%*", fieldwidth, num_to_print);

However, I can't figure out how to get the number of digits in the
number (which I would then assign to the 'fieldwidth' variable above).

I know I don't have to explicitly set the field width with printf, but
I would like very much to know how to discover it.

Can anyone suggest how I might get the number of digits for a numeric
variable?

Thanks...


I realize I'm late responding here but first, I don't see your problem.

printf("%d\n", num_to_print);

...will print the 'right' number of digits left-justified.

12
3456
7
876

I propose that fieldwidth is not calculated, but defined by the format.
The 'f' in printf is for format.

This allows right-justifying a column of numbers..

int fieldwidth = 5;
printf("%*d\n", fieldwidth, num_to_print);

12
3456
7
876

Of course, I might have missed the whole point.
--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1474
by: Philippe Rousselot | last post by:
Hi, On a page, I have a form with a variable number of fields. to print these fields, I have such a code : while ($i !=0){ echo '<td> <input type="text" name="component'.$i.'" size="20" value="" maxlength="70"> </td><br> <td> <input type="text" name="quantity'.$i.'" size="20" value="" maxlength="70"><br>
10
2334
by: David Casey | last post by:
I'm working on a program for my C++ class and have it all written and working except for one part. I need to compare two numeric variables to determine decimal accuracy between them. For example: pi = 3.14159... mynum = 3.14226... The mynum is accurate to 2 decimal places compared to pi. I could figure this out easy with a char array since I could just take a character one at a time from each array and compare it. However with a...
11
3143
by: abs | last post by:
Input field of the form. How to check which number this field has ? I mean the order number, like variable elementNumber in document.forms.elements ? Is it possible to check without looping and comparing some attributes in every loop ? Best regards, ABS
2
1843
by: Jon Martin Solaas | last post by:
Hi, I have a general document somewhat like this: -------------------------------------- <root> <level1> <level2> <interestingstuff number="2"/> <interestingstuff number="3"/> <interestingstuff number="1"/>
6
1562
by: ven | last post by:
hello i want to get current record in MS SQL table with identity column, let say i put somethin using INSERT INTO and then i want to know current number in identity column how can i put this number into variable in vbscript ? Ven
6
7362
by: Jovo Mirkovic | last post by:
Hi, I have to make a program which will generate 100,000 different ID numbers (for example 2345-9341-0903-3432-3432 ...) It must be really different, I meen it can not be a similar (like 2345-9341-0903-3432-343<b>1</b>) Does exist some algorithm for that... Thanks.
14
1455
by: Gary | last post by:
Hi, I am trying to format a number to the following, "10" to "10." using, Printline(1, format(10, "###.###)) naturally this does not achieve the desired result, I know if I do this, Printline(1, format(10, "###.0##)) I get this "10.0" but I do not need the trailing "0" any ideas on how to get from this "10" to this "10."? Thanks,
4
4218
by: =?Utf-8?B?Vmlua2k=?= | last post by:
Hello Everyone, I am trying to convert the digits to even number so for example if I have 3 digit number, I want it to be 4 digit and If I have 5 digit number, I want it to be 6 digit. How can i do it in C# Below is what I am trying to di number = 123 I want it to be
0
1237
by: John Doe77 | last post by:
Hi, Given a phone number I need to print out all the word representation combinations possible from that phone number. Digits translate into chars like the following: 1 = 1 2 = A B C 3 = D E F 4 = G H I 5 = J K L 6 = M N O
2
9756
by: jeanbdenis | last post by:
Hi Folks, I have been struggling with this issues for the last couple of days. I have a java application which does an update to the database every 5 mins. The data written to the database does not change much from one minute to the next. Just the timestamp. While this application runs 24/7, the error occurs once or twice a day (It's an intermittent problem which I have not been able to replicate in my dev environment) below is the...
0
9645
marktang
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10325
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8972
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.