#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 Overflowc - conversion of string to decimal - Stack Overflow
How to convert a large decimal number in string form to base 2^16 in C?
c# - Convert string to decimal, keeping fractions - Stack Overflow
c - Converting decimal integers to a string representation in an arbitrary base between 2 and 26 - Code Review Stack Exchange
Videos
#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;
}
int number = 254;
int back=0,i=0;
char ch='\0';
char string[10];
for(i=0;(number/10)==0;i++){
back=number%10;
ch=(back*pow(10,i)+48);
string[i]=ch;
}
- divide number per 10
- get the rest( with % ) the rest is the digit you want starting from the right
- cast the digit to char +48(ascii 0)
- add to string
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.
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.
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.
Hmm... I can't reproduce this:
using System;
class Test
{
static void Main()
{
decimal d = decimal.Parse("1200.00");
Console.WriteLine(d); // Prints 1200.00
}
}
Are you sure it's not some other part of your code normalizing the decimal value later?
Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:
using System;
using System.Globalization;
class Test
{
static void Main()
{
decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
}
}
Hello i was have the same issue, but it is easly, just do this:
string cadena="96.23";
decimal NoDecimal=decimal.parse(cadena.replace(".",","))
I think this is beacuse the notation that accept C# on decimal numbers are with a ","
#include <stdio.h>
int main() {
unsigned f = 65535; // initial value
// this will do the printf and ff >>= 8 until f <= 0 ( =0 actually)
do {
printf("%c", f & 0xff); // print once char. The &0xff keeps only the bits for one byte (8 bits)
f >>= 8; // shifts f right side for 8 bits
} while (f > 0);
}
Consider the value 65535, or 0xffff in hexadecimal, meaning its positive value takes 2 bytes that are 0xff and 0xff
- print of
f & 0xffkeeps only the 8 LSb, (0xffff & 0xff = 0xff) f >> = 8shifts the value 8 bits to the right, 0xffff becomes 0x00ff (the 'ff' right side are gonef > 0is true sincef == 0xffnow
Next loop is the same, but f >>= 8 shifts 0x00ff to the right => 0x0000, and f is null.
Thus the f > 0 condition is wrong and the loop ends.
What you're looking for is bit masking: (x >> 8) & 0xFF for
the high order byte, and (x & 0xFF) for the lower. (Actually,
if int has 32 bits, it's (x >> 24) & 0xFF for the high order
byte. But given the values, and what you say your expecting,
you probably want the second byte, and not the high order byte.)
You can use this function instead of atoi:
char a3toc(const char *ptr)
{
return (ptr[0]-'0')*100 + (ptr[1]-'0')*10 + (ptr[0]-'0');
}
So, a3toc("102") will return the same thing as (char) 102, which is an 'f'.
If you don't see why, substitute in the values: ptr[0] is '1', so the first part becomes ('1'-'0')*100 or 1*100 or 100, which is what that first 1 in 102 represents.
Tokenize the input string. I'm assuming you are forcing that every letter MUST be represented in 3 characters. So break the string that way. And simply use explicit type casting to get the desired character.
I don't think I should be giving you the code for this, since it is pretty easy and seems more like a Homework question.
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?
You can use sprintf to do it, or maybe snprintf if you have it:
char str[ENOUGH];
sprintf(str, "%d", 42);
Where the number of characters (plus terminating char) in the str can be calculated using:
(int)((ceil(log10(num))+1)*sizeof(char))
As pointed out in a comment, itoa() is not a standard, so better use the sprintf() approach suggested in the rival answer!
You can use the itoa() function to convert your integer value to a string.
Here is an example:
int num = 321;
char snum[5];
// Convert 123 to string [buf]
itoa(num, snum, 10);
// Print our string
printf("%s\n", snum);
If you want to output your structure into a file there isn't any need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
You can use the decimal.ToString override to specify a formatting.
decimal amount = 120.5m;
string str = amount.ToString("0.00");
This can also be used when using String.Format.
Console.WriteLine("{0:0.00}", amount);
In the case of your first and second rule, it cannot be done on one line.
decimal amount = 120.5m;
string str = amount.ToString("0.00").Replace(".00", String.Empty);
The following extension method should satisfy you requirements. The comments on the code was provided in OP and comments.
public static string ToFormattedString(this decimal d)
{
//The comma is not mandatory. but
var s = d.ToString();
var tokens = s.Split(new[]{"."}, StringSplitOptions.RemoveEmptyEntries);
//if there are no decimal points 12 then there should no be any zeros and periods (.)
if (tokens.Length == 1)
return s;
//I need to remove trailing zeros
var places = tokens[1].TrimEnd('0');
if (places.Length == 0)
return tokens[0];
//if there is only one decimal point ex- 0.5 then it should be displayed as 0.50
if (places.Length == 1)
return d.ToString("F2");
var format = string.Format("F{0}", places.Length);
return d.ToString(format);
}
Used like this
var x = new decimal[]{120.5m, 110, 25.356m};
foreach (var item in x)
Console.WriteLine("{0} => {1}", item.ToString(), item.ToFormattedString());
Output:
120.5 => 120.50
110 => 110
25.356 => 25.356