#include <stdio.h>
#include <stdlib.h>

int i2a(char *s, int n){
    div_t qr;
    int pos;

    if(n == 0) return 0;

    qr = div(n, 10);
    pos = i2a(s, qr.quot);
    s[pos] = qr.rem + '0';
    return pos + 1;
}

char* my_itoa(char *output_buff, int num){
    char *p = output_buff;
    if(num < 0){
        *p++ = '-';
        num *= -1;
    } else if(num == 0)
        *p++ = '0';
    p[i2a(p, num)]='\0';
    return output_buff;
}

int main(void){
    int number = -254;
    char string[12];
    printf("%s", my_itoa(string, number));
    return 0;
}
Answer from BLUEPIXY on Stack Overflow
๐ŸŒ
Online String Tools
onlinestringtools.com โ€บ convert-string-to-decimal
Convert a String to Decimal โ€“ Online String Tools
Quickly convert a string to a decimal string. ... Quickly convert a decimal string to a string.
๐ŸŒ
C For Dummies
c-for-dummies.com โ€บ blog
From Decimal Value to a String | C For Dummies Blog
May 14, 2022 - Variable buffer is declared as static at Line 6 to ensure that its contents arenโ€™t discarded when the function returns. The snprintf() function at Line 9 converts float value a into a string in buffer. The while loop at Line 12 locates the decimal within the string, the dividing character between the valueโ€™s integer and fractional part.
Discussions

c - conversion of string to decimal - Stack Overflow
I am using RS232 serial communication to rotate the motor. The serial communication is done in strings but i need decimal value for it. Any clues how to proceed.I am coding in c language.i tried us... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert a large decimal number in string form to base 2^16 in C?
Option 1: use a "big math" library. Option 2: roll your own basic addition routines, and build from there. Your big numbers will represented by a uint16_t[]. You add two base-N numbers by: adding the 1's column (potentially producing an overflow if the result exceeds N), then adding the N's column (potentially with the overflow from above, and potentially producing another overflow if the result exceeds N2) then adding the N2 's column, etc. etc. In your format, your 1's column is stored in array index [0], your N's columns is stored in [1], your N2 's column is stored in [2], etc. Adding two numbers So to add two uint16_t[] numbers, all you need to do is: add the two [0] values together, and if this exceeds your base (216) then you set an overflow flag, otherwise clear the overflow flag. add the two [1] values and the previous overflow together, and if this exceeds your base (216) then you set an overflow flag, otherwise clear the overflow flag. add the two [2] values and the previous overflow together, and if this exceeds your base (216)... ...etc. etc... eventually you run hit the end of the input arrays, and if the overflow is set then you need to extend the output array length by 1, and put the overflow there. Multiplying numbers Construct a lookup table, up to the maximum number of decimal digits you expect to handle. You can readily extend this to "arbitrary number of digits" but for now maybe cap it at 20 digits or so to prove the process. Construct a uint16_t[] number for "0" (your array is all zeros) Construct a uint16_t[] number for "1" (your array is all zeros, except for index [0] = 1) Save this in a lookup table at position [0] Construct a uint16_t[] number for "10" by adding your "1" to your "0" ten times. Save this in a lookup table at position [1] Construct a uint16_t[] number for "100" by adding your "10" to your "0" ten times. Save this in a lookup table at position [2] Construct a uint16_t[] number for "1000" by adding your "100" to your "0" ten times. Save this in a lookup table at position [4] Construct a uint16_t[] number for "10000" by adding your "1000" to your "0" ten times. Save this in a lookup table at position [4] ...etc. (Here you're obviously using your "add" routine that you wrote earlier! So now you have a lookup table of uint16_t[], where each subsequent index representing the next power of ten. Parse your base-10 text input Read your text input per-digit, 1's digit first, moving up through all the digits. Construct a uint16_t[] number for "0" (your array is all zeros). This will be your running sum that will eventually be your final output. read the 1's digit, and whatever its value is how many times you add to your running sum from position [0] of your lookup created in the "multiply" section above read the 10's digit, and whatever its value is how many times you add to your running sum from position [1] of your lookup created in the "multiply" section above read the 100's digit, and whatever its value is how many times you add to your running sum from position [2] of your lookup created in the "multiply" section above ... etc. (Again you're obviously using your "add" routine that you wrote earlier) Below 232, your uint16_t[] (if stacked end-on-end) should be bitwise identical to a uint32_t Below 264, your uint16_t[] (if stacked end-on-end) should be bitwise identical to a uint64_t More on reddit.com
๐ŸŒ r/C_Programming
2
0
August 25, 2022
c# - Convert string to decimal, keeping fractions - Stack Overflow
I am trying to convert 1200.00 to decimal, but Decimal.Parse() removes .00. I've tried some different methods, but it always removes .00, except when I supply a fraction different than 0. string v... More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - Converting decimal integers to a string representation in an arbitrary base between 2 and 26 - Code Review Stack Exchange
This code takes an integer and returns a string representing the value in a different base. The value for the base can range between 2 and 26. I have had someone already look over this code and the... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
October 20, 2014
Top answer
1 of 2
4

Use the strtoXXX() family of functions. If you need int, long or long long or their unsigned variants:

long l = strtol("1234567", NULL, 10);
long long ll = strtoll("1234567", NULL, 10);
unsigned long l = strtoul("1234567", NULL, 10);

If you need a float, double, or long double use this:

float f = strtof("3.1415927", NULL);
double d = strtod("3.1415927", NULL);

Manuals here and here.

2 of 2
1

Usually given a string:

char * myStr= "123";

the way to obtain it's value as an int is:

int value=atoi(myStr);

Some things important to notice:

the following include is necessary:

#include <stdlib.h>

and you must be sure that your string is a null terminated string otherwise atoi will crash you program.

You didn't gave us much information but if you're programming a microcontroller (I suspect that since you told us about a motor) you maybe won't want to use stdlib. In that case you might have use a costum function.

Please take a look at the code bellow:

int stringToInt(char* nrStr){
int nrChars=0;
while(nrStr[nrChars]!='\0'){
    nrChars++;
}


int result=0;
int i=0;
while(nrStr[i]!='\0'){//while you dont get to the end of the string
    int digit=nrStr[i]-48;//48 is zero ascii code
    int exp=nrChars-i-1;
    int add=digit*power(10,exp);
    result+=add;
    i++;


}
return result;


}
int power(int base, int exp){
int ret=1;
int i;
for(i=0;i<exp;i++){
    ret*=base;
}
return ret;
}

This does not use any library functions and does the job. I've done it in 3 minutes and it may have some small error, it's not very efficient and does not verify possible errors, but in principle if you pass the strinToint function a well formed integer as a null terminated string it will output the correct value.

If you're using a library that does have some implementation of a power function do use it instead of the one I gave you since it is not efficient at all.

One last note: if you for some reason need to use it in other basis lets say octal basis, you have to chance the line:

int add=digit*power(10,exp);

to:

 int add=digit*power(8,exp);

for hexadecimal this will not work, and implementation of such a function will be significantly different.

๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ how to convert a large decimal number in string form to base 2^16 in c?
r/C_Programming on Reddit: How to convert a large decimal number in string form to base 2^16 in C?
August 25, 2022 -

Hey everyone, I am currently trying to do some work with Big Numbers in C. Basically, I have an input of string digits in base 10 that is arbitrarily long (longer than long long int), and I am trying to store the data in an array of uint16_t types.

My original plan was to do atoi on individual digits, multiplying it by its location in the string (base 10), and adding it to the 0th value, and then managing overflows from there. So if it was 543, I would put the 3 in the first slot, then add 40 to make it 43 (check for overflow), then add 500 to make it 543 (check for overflow). If there were more numbers, I would keep going, and if there was any instance of overflow I would increment the next significant value by 1, check THAT for overflows, and keep going.

The problem is that when the numbers get really long, I canโ€™t multiply the digit in the string by its place, as that is larger than INT_MAX, or even larger than long long int. How can I find which section of the uint16_t array to put the value to ensure no overflows, and allow me to keep cascading the โ€œcarry the 1โ€ idea?

Alternatively, is there a flat out better way to do this? I have seen some stuff online about shortcuts you can take to convert an int to a base 2n, however I donโ€™t think it works if the decimal is stored in string notation.

Top answer
1 of 2
7
Option 1: use a "big math" library. Option 2: roll your own basic addition routines, and build from there. Your big numbers will represented by a uint16_t[]. You add two base-N numbers by: adding the 1's column (potentially producing an overflow if the result exceeds N), then adding the N's column (potentially with the overflow from above, and potentially producing another overflow if the result exceeds N2) then adding the N2 's column, etc. etc. In your format, your 1's column is stored in array index [0], your N's columns is stored in [1], your N2 's column is stored in [2], etc. Adding two numbers So to add two uint16_t[] numbers, all you need to do is: add the two [0] values together, and if this exceeds your base (216) then you set an overflow flag, otherwise clear the overflow flag. add the two [1] values and the previous overflow together, and if this exceeds your base (216) then you set an overflow flag, otherwise clear the overflow flag. add the two [2] values and the previous overflow together, and if this exceeds your base (216)... ...etc. etc... eventually you run hit the end of the input arrays, and if the overflow is set then you need to extend the output array length by 1, and put the overflow there. Multiplying numbers Construct a lookup table, up to the maximum number of decimal digits you expect to handle. You can readily extend this to "arbitrary number of digits" but for now maybe cap it at 20 digits or so to prove the process. Construct a uint16_t[] number for "0" (your array is all zeros) Construct a uint16_t[] number for "1" (your array is all zeros, except for index [0] = 1) Save this in a lookup table at position [0] Construct a uint16_t[] number for "10" by adding your "1" to your "0" ten times. Save this in a lookup table at position [1] Construct a uint16_t[] number for "100" by adding your "10" to your "0" ten times. Save this in a lookup table at position [2] Construct a uint16_t[] number for "1000" by adding your "100" to your "0" ten times. Save this in a lookup table at position [4] Construct a uint16_t[] number for "10000" by adding your "1000" to your "0" ten times. Save this in a lookup table at position [4] ...etc. (Here you're obviously using your "add" routine that you wrote earlier! So now you have a lookup table of uint16_t[], where each subsequent index representing the next power of ten. Parse your base-10 text input Read your text input per-digit, 1's digit first, moving up through all the digits. Construct a uint16_t[] number for "0" (your array is all zeros). This will be your running sum that will eventually be your final output. read the 1's digit, and whatever its value is how many times you add to your running sum from position [0] of your lookup created in the "multiply" section above read the 10's digit, and whatever its value is how many times you add to your running sum from position [1] of your lookup created in the "multiply" section above read the 100's digit, and whatever its value is how many times you add to your running sum from position [2] of your lookup created in the "multiply" section above ... etc. (Again you're obviously using your "add" routine that you wrote earlier) Below 232, your uint16_t[] (if stacked end-on-end) should be bitwise identical to a uint32_t Below 264, your uint16_t[] (if stacked end-on-end) should be bitwise identical to a uint64_t
2 of 2
3
b * 10 equals (b * 2 * 2 + b) * 2. Maybe you can do with just longhand addition and a routine to shift left 1 bit.
Top answer
1 of 1
3
  • The cardinal sin

    An assignment tmp_string[tmp_string_i] = remainder; may write beyond an allocated memory. Consider a case of buffer_size being equal to 0. You must test tmp_string_i before the assignment. I don't know what exactly someone had in mind, but you are definitely committing one.

  • Unnecessary variables

    decimal_number is passed by value; you can mutilate it as much as you want. There is no need to have dividend.

    Reversal can be done in-place. There is no need for tmp_string at all. tmp_string_i shall also be gone.

  • Finding digits

    Executing division dividend / base twice per iteration looks wrong; special-case of the last digit looks also wrong. Using do-while solves both wrongs:

        do {
            output[output_i++] = int_to_char(dividend % base);
            number = number / base;
        } while (number != 0);
    
  • No raw loops

    Most loops represent an important algorithm, which deserves to be factored out in a function of its own, for further reuse and for giving it a name. In your case, the loop under the //copy tmp_string to output in reverse order comment implements an algorithm known as reverse.

All that said, this is

  • Misc

    • The returned string should be terminated by '\0', or its actual length be returned.

    • The code happily converts numbers to a base up to 36 (10 digits and 26 letters). I see no reason to limit a base to 26.

    • Return codes 0,-1,-2 should be defined as named constants.

    • Size variables (e.g. buffer_size) should be unsigned, or better yet of type size_t.

    • The decimal_number parameter is not decimal. It is just number. Need to be renamed accordingly.

Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ c-program-to-convert-a-number-to-a-string
C Program to convert a number to a string
July 30, 2019 - #include<stdio.h> main() { char str[20]; //create an empty string to store number float number; printf("Enter a number: "); scanf("%f", &number); sprintf(str, "%f", number); //make the number into string using sprintf function printf(" You have entered: %s", str); }
๐ŸŒ
Reddit
reddit.com โ€บ r/csharp โ€บ convert string to decimal keeping fractions.
r/csharp on Reddit: Convert string to decimal keeping fractions.
November 11, 2020 -

Lets say i have this string

string s = "33.000";

i need to convert it to decimal with this format

decimal d = 33.000;

I am doing convert.toDecimal but receive decimal formating like this 33.00 so i lost last zero. any idea?

Top answer
1 of 5
7
Display format is only relevant when you display it. To convert a string to a decimal, you'd just do: var dec = Convert.ToDecimal("33.000"); When you display it, you could do: Console.WriteLine(dec.ToString("###,###.000"));
2 of 5
3
33.000 and 33.0 are, depending on how a value is stored, the same or not the same. With strings, "33.000" and "33.0" are obviously not the same, while 33.000 and 33.0 are absolutely equal if we're talking about floats. But how do you think decimals are stored? The answer you can find in this stackoverflow question. Basically it's stored as 1 sign bit + a 96 bit integer + 31 bit to say how much it is shifted to the right. That means, it's possible to store 33.000 as (+, 33000, 0) or (+ 330000, 1) etc. To see the binary representation of a decimal, you can use the method GetBits(), you'll get an array of four ints. Armed with this, you can check if the amount of digits you see printed are event dependent on the binary representation. And the answer is: yes it is. If not, you need to format the decimal manually, when you print it. You can create your own format extension method for decimals to not have code duplication. If the amount of digits is dependent on the binary representation, then you either need to write your own parsing method, that handles parsing how you want it to, or you need to check if convert.ToDecimal can be configured somehow, maybe via additional parameters. I just checked and I got the amount of digits from the string correctly Console.WriteLine(Convert.ToDecimal("33,000")); Console.WriteLine(Convert.ToDecimal("33,0")); Console.WriteLine(decimal.Parse("33,000")); Console.WriteLine(decimal.Parse("33,0")); Can you check that?ยจ You might have to replace the commas for dots.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 236749
convert string to decimal - C++ Forum
May 11, 2018 - there is no 'conversion' apart from forcing it to print the integer instead of the character value, which you can do with (int) variable cast in the print: cout << (int)var << endl; or for a string..
๐ŸŒ
Online String Tools
onlinestringtools.com โ€บ convert-decimal-to-string
Convert Decimal to a String โ€“ Online String Tools
Instant Copy-to-clipboardCopy the string to clipboard with a single click. ... This tool converts decimal numbers to a human-readable ASCII, UTF8 or Unicode string.
๐ŸŒ
Udemy
blog.udemy.com โ€บ home โ€บ c string to int: simple ways to convert to numeric values
C String to Int: Simple Ways to Convert to Numeric Values - Udemy Blog
October 25, 2025 - In this case, the string is an array of characters pointed to by num. Then, we calculate the length of the string using the strlen() function. Next, we loop through the string and convert the string into decimal values.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ what-is-the-best-way-in-c-to-convert-a-number-to-a-string
What is the best way in C to convert a number to a string? - GeeksforGeeks
June 2, 2017 - #include<stdio.h> int main() { char result[50]; float num = 23.34; sprintf(result, "%f", num); printf("\n The string for the num is %s", result); getchar(); } You can also write your own function using ASCII values of numbers.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-convert-a-decimal-value-to-a-string-in-c-sharp
How to convert a decimal value to a string in C#
Decimal.ToString() is a method in C# that is called on decimal values. It converts a numeric value that is a decimal to a string.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ reference โ€บ string โ€บ to_string
std::to_string - string
string to_string (int val);string to_string (long val);string to_string (long long val);string to_string (unsigned val);string to_string (unsigned long val);string to_string (unsigned long long val);string to_string (float val);string to_string (double val);string to_string (long double val); ... Returns a string with the representation of val. The format used is the same that printf would print for the corresponding type:
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 60937-convert-char-string-decimal-equivalent-eg-=-chr-97-a.html
Convert char string to decimal equivalent (eg: a = chr(97))...
Hi, I just want to say THANK YOU! That particular question's answer isn't easily found on the internet!!! The first code example was the one I was after: ... char somechar = 'a'; int charval = somechar; printf("%c = %d\n",somechar,charval); The atoi() just kept returning the integer 0 for every character I passed through it. Such simple methods are so easily overlooked! Thanks again! Blueprint. ... I send out the string "FFFD" trying to convert it to hits integer.