When I convert an unsigned 8-bit int to string then I know the result will always be at most 3 chars (for 255) and for an signed 8-bit int we need 4 chars for e.g. "-128".

Now what I'm actually wondering is the same thing for floating-point values. What is the maximum number of chars required to represent any "double" or "float" value as a string?

Assume a regular C/C++ double (IEEE 754) and normal decimal expansion (i.e. no %e printf-formatting).

I'm not even sure if the really small number (i.e. 0.234234) will be longer than the really huge numbers (doubles representing integers)?

Depends on what you mean by "represent". Decimal fraction don't have exact floating-point representations. When you convert decimal fraction -> binary fraction -> decimal, you do not have exact decimal representations and will have noise bits at the end of the binary representation.

The question didn't involve starting from decimal, but all source code (and must user input) is decimal, and involves the possible truncation issue. What does "exact" mean under these circumstances?

Basically, it depends on your floating point representation.

If you have 48 bits of mantissa, this takes about 16 decimal digits. The exponent might be the remaining 14 bits (about 5 decimal digits).

The rule of thumb is that the number of bits is about 3x the number of decimal digits.

http://en.wikipedia.org/wiki/IEEE_754-1985

The longest representable double:

-2.2250738585072020E−308

has 24 chars.

You can control the number of digits in the string representation when you convert the float/double to a string by setting the precision. The maximum number of digits would then be equal to the string representation of `std::numeric_limits<double>::max()`

at the precision you specify.

```
#include <iostream>
#include <limits>
#include <sstream>
#include <iomanip>
int main()
{
double x = std::numeric_limits<double>::max();
std::stringstream ss;
ss << std::setprecision(10) << std::fixed << x;
std::string double_as_string = ss.str();
std::cout << double_as_string.length() << std::endl;
}
```

So, the largest number of digits in a `double`

with a precision of 10 is 320 digits.

The standard header `<float.h>`

in C, or `<cfloat>`

in C++, contains several constants to do with the range and other metrics of the floating point types. One of these is `DBL_MAX_10_EXP`

, the largest power-of-10 exponent needed to represent all `double`

values. Since `1eN`

needs `N+1`

digits to represent, and there might be a negative sign as well, then the answer is

```
int max_digits = DBL_MAX_10_EXP + 2;
```

This assumes that the exponent is larger than the number of digits needed to represent the largest possible mantissa value; otherwise, there will also be a decimal point followed by more digits.

**CORRECTION**

The longest number is actually the smallest representable negative number: it needs enough digits to cover both the exponent and the mantissa. This value is `-pow(2, DBL_MIN_EXP - DBL_MANT_DIG)`

, where `DBL_MIN_EXP`

is negative. It's fairly easy to see (and prove by induction) that `-pow(2,-N)`

needs `3+N`

characters for a non-scientific decimal representation (`"-0."`

, followed by `N`

digits). So the answer is

```
int max_digits = 3 + DBL_MANT_DIG - DBL_MIN_EXP
```

For a 64-bit IEEE double, we have

```
DBL_MANT_DIG = 53
DBL_MIN_EXP = -1023
max_digits = 3 + 53 - (-1023) = 1079
```

You can use `snprintf()`

to check how many chars you need. `snprintf()`

returns the number of chars needed to print whatever is passed to it.

```
/* NOT TESTED */
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char dummy[1];
double value = 42.000042; /* or anything else */
int siz;
char *representation;
siz = snprintf(dummy, sizeof dummy, "%f", value);
printf("exact length needed to represent 'value' "
"(without the '\\0' terminator) is %d.\n", siz);
representation = malloc(siz + 1);
if (representation) {
sprintf(representation, "%f", value);
/* use `representation` */
free(representation);
} else {
/* no memory */
}
return 0;
}
```

**Note**: `snprintf()`

is a C99 function. If a C89 compiler provides it as an extension, it may not do what the above program expects.

*Edit*: Changed the link to `snprintf()`

to one that actually describes the functionality imposed by the C99 Standard; the description in the original link is wrong.

2013: Changed the link *back* to POSIX site which I prefer over the site of the first edit.

1024 is not enough, the smallest negative double value has 1077 decimal digits. Here is some Java code.

```
double x = Double.longBitsToDouble(0x8000000000000001L);
BigDecimal bd = new BigDecimal(x);
String s = bd.toPlainString();
System.out.println(s.length());
System.out.println(s);
```

Here is the output of the program.

```
1077
-0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004940656458412465441765687928682213723650598026143247644255856825006755072702087518652998363616359923797965646954457177309266567103559397963987747960107818781263007131903114045278458171678489821036887186360569987307230500063874091535649843873124733972731696151400317153853980741262385655911710266585566867681870395603106249319452715914924553293054565444011274801297099995419319894090804165633245247571478690147267801593552386115501348035264934720193790268107107491703332226844753335720832431936092382893458368060106011506169809753078342277318329247904982524730776375927247874656084778203734469699533647017972677717585125660551199131504891101451037862738167250955837389733598993664809941164205702637090279242767544565229087538682506419718265533447265625
```

"What is the maximum length in chars needed to represent any double value?"

The exact answer to this question is: 8 ASCII chars - in a hexadicimal format, excluding the '0x' prefix - 100% accuracy :) (but it's not just a joke)

The usable precision of IEEE-754 double is around 16 decimal digits - so excluding educational purposes, representations longer than that are just a waste of resources and computing power:

Users are not getting more informed when they see a 700-digit-number on the screeen.

Configuration variables stored in that "more accurate" form are useless - every single operation on such number will destroy the accuracy. (excluding changing the sign bit)

If someone needs better *real* precision, then there's 80-bit long double with around 18-digit accuracy or f.e. libquadmath.

Regards.

Similar Questions

I have an area of connected squares (img to the left), and want to find the maximum number of double squares that could be fitted into the area (img to the right). My approach is to represent the or

I have been using minMaxLoc to compute the maximum value of the data obtained by running a laplacian filter over a grayscale image. My simple intention is to roughly estimate the sharpness. I encounte

I need to know the maximum length of a textbox in ssrs. How much data can it accomodate?

From java documentation int has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). I have a class Test.java. public class Test { public static void main(String[] args)

I have the length of a representation of an integer in an arbitrary base. Say the length is 15, and the base is 36. I'd then like to work out how long a representation of said integer would be in anot

what is maximum length of string parameter that can be passed by ajax to web method. Is there any limit for parameter value length?

What is the decimal value of the largest positive integer we can represent in 7 bits? My thinking is that it would be 1111111 = 127. Can anyone confirm my suspicions?

Possible Duplicate: What is the maximum length of a URL? Hi I want to log referrer into my database , i want to know what the maximum length is for referrer ?

What is the maximum length of the cable can be for infiniband(RDMA)? For example. Here have said, that it can be up to 10 M for a four-channel copper cable. And using the Connects Cables using fiber,

I'm having this error when using a long GET request: SEVERE: GRIZZLY0039: Request URI is too large. java.nio.BufferOverflowException What is the configuration I have to change for Glassfish 3.1? I t

How would you find the maximum long value supported on your system within an application in Objective-C? That is, how do we determine what the largest value is that long can represent?

What is the best algorithm to get all possible string combinations from a given array with a minimum & maximum length value. Note: This adds complexity since the value is variable unlike the quest

Should i still follow the rule of maximum line length of 79 char while coding in python. if yes so when to use enter and \ for line breaking. eg, qy = MyModel.objects.filter(name='abcd', modified_on_

This question is a continuation of a previous thread to compare two lists with the same length: Is there any efficient easy way to compare two lists with the same length with Mathematica? Given two li

I am using CPLEX Java library in my optimization code. In CPLEX library, user can change the default value of gap value by calling setParam(DoubleParam.EpGap, 0.01) etc. What is the max value that a u

I'm attempting to change a random value in a double. The chosen value is random for the length size of the variable. The method below returns the exact same parameter it takes. Any help please? I want

I have an array like this: arr = [{id: 1, name: 'John' }, {id: 2, name: 'Sam' }, {id: 3, name: 'Bob' }] I need to check if any of arr objects have name Sam. What is the most elegant way? I can only t

This question already has an answer here: What is the longest regular expression you have seen [closed] 3 answers I am wondering: Is the regular expression (itself) somehow limited? I don't mea

I want to build pattern for preg_match that will match any string with length 1 - 40 chars. I found this: ^[^<\x09]{1,40}\Z But with that one I recieve this error message: function.preg-match]: U

In a C program that doesn't use recursion, it should be possible in theory to work out the maximum/worst case stack size needed to call a given function, and anything that it calls. Are there any free

Does anyone know a portable way for Python to determine a system's maximum command line length? The program I'm working on builds a command and feeds it to subprocess. For systems with smaller command

I am using Vim 7.3 on Windows 7. The documentation on path says The maximum length is limited. How much depends on the system, mostly it is something like 256 or 1024 characters. However when I exec

I need to get the maximum value out of this code, but it's really screwy. Anyone got any suggestions? import java.util.Scanner; public class Test{ public static void main(String args[]) { Scanner scan

I have to send a decimal in string format. The maximum length of the string is 15. How can I do this by rounding to the best fit? eg: 1111111111111119 = 111111111111112 11111111111111.111 = 111111

I'd like to store an scrypt-hashed password in a database. What is the maximum length I can expect?

What is the maximum URL length you can pass to the Wininet function, HttpOpenRequest?

I'm using RubyMine which informs me that unsubscribe_from_all_notifications ...is too long for a method name. What's the max length?

In Emacs, how can I enforce a maximum line length of, say, 80 characters? I want it to insert proper line breaks in my code, much like fill-paragraph for text, if possible, with the correct insertion

I have declared a column of type NVARCHAR(MAX) in SQL Server 2008, what would be its exact maximum characters having the MAX as the length?

Searched the docs, but to no avail. What is the maximum length for an enumeration value, i.e. the string literal?

Let's say we have a table in SQL Server with primary key of integer type. What happens if the number of rows in table exceeds maximum value for int data type?

Referring to this question maximum-number-of-processes-in-linux I under stand that kernel.pid_max affects the maximum value for PID and max user processes in /etc/security/limits.conf file affects tot

Let's say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2] What is the best way to find the minimum or maximum value in that Array? Right now, to get the maximum, I am looping through the Array, and

What is the maximum length of data I can put in a BLOB column in MySQL?

I am trying to represent any XML schema into data structure, which maintain the hierarchy of that schema and positions of each element in the schema. Any suggestions?

My dataset has several string columns which their maximum string lengths are known, and some of them are only a single char. I tried to use varchar with specified length like varchar(5) to store them,

Possible Duplicate: What is the maximum length of a C#/CLI identifier? When generating dynamic assemblies and types, what is length restriction on the type name?

what is the maximum length of a class name in objective-c? I could not find any hints in the xcode doc-sets and google was no help either. I am currently writing some runtime helpers, and it would be

I need to save the currency symbol field from a Zend_Currency object to a DB. I need to set a maximum length for the DB field and I'm wondering what might be a safe value for this particular type of d

Saw these variables in the debugger and I'm not sure what they do.

I need your help to solve a problem. This is part of a coding exercise, that I couldn't solve completely. Imagine we have the following graph : I need to build a class that calculates the maximum len

In data formats where all underlying types are strings, numeric types must be converted to a standardized string format which can be compared alphabetically. For example, a short for the value 27 coul

Suppose there is only one single double value written into a file in binary format. How can I read that value using C# or Java? If I have to find a double value from a huge binary file, what technique

I asked a question a while back about the Maximum string length of Excel Print Area : Maximum String Length of PrintArea in Excel Print Area is set at 255, for Excel 2010. I think this is a read-only

I wonder what is the maximum number of SQLiteOpenHelper version? For the version code, I found a SO topic says that this number is just an integer to indicate version of the code base. There will be n

By another question about the maximum number of files in a folder, I noticed that DirectoryInfo.GetFiles().Length is returning a System.In32, but the Maximum value of a Int32 is 2.147.483.647 (Int

In general, what could cause a double free in a program that is does not contain any dynamic memory allocation? To be more precise, none of my code uses dynamic allocation. I'm using STL, but it's muc

Hey guys I thought I ran into something where sql would only sort up to a certain length of a varchar or nvarchar. Does anyone know that #?

How can I know what is the maximum assignable value for a variable from the the type of unsigned long int?

I have a table in mysql with many columns and I want to see maximum length of values. My purpose is that I do know that some of data is truncated when insert and I want to increase varchar length. But