I'm receiving a percentage from a machine controller over rs232, it insists on sending me a percentage to 9 decimal places.
I only want a percentage integer no decimal.
I'm trying to think of a neat way to convert 10.000000001% to 10%.
Can't you just use just perform a digit by digit ASCII to int conversion (accounting for weighting of each digit using a case statement to associate each ASCII digit with a numerical value) and stop when the decimal is encountered (or start at the decimel point, depending on which direction you want to move through the digits)?
Basically, pretend you're actually converting an ASCII int into to an int but use the decimal as the termination character instead of the typical null character.
atoi() generates an error, I think its the decimal point that messes it up.
Rounding would be nice.
I think I'll try indexOf() and pull the figures out into a buffer, it does seem 'unclean'.
atof() is the one you need, but it's a crass way of doing it, You would be better of writing a small routine that runs through the ascii number until a decimal place or a CR is reached.... Doing it this way will allow you to look at the first decimal digit and round it yourself..
There is a cool function in the string library that will check a string for the first occurrence of '.' and the result is the place in the string.. Then you can add the figures as you can determine the decimal weights beforehand.. strcmp() will accept the delimeter of your choice and return its position..
the classic method for rounding a floating point number to integer is simply to add 0.5 to the float value and then truncate it to integer. No need to mess around with 'If" constructs.
the classic method for rounding a floating point number to integer is simply to add 0.5 to the float value and then truncate it to integer. No need to mess around with 'If" constructs.
I'm not especially familiar with this version of C, but I assumed (yes I know, dangerous to assume) that you can convert a string to a float, add 0.5 and then truncate to integer.
Normally code written specifically for a task is usually smaller and faster than using libraries. The code I posted above has the advantage of rounding and will definitely be more compact and faster than a float method and probably the itoa method as well.
Normally code written specifically for a task is usually smaller and faster than using libraries. The code I posted above has the advantage of rounding and will definitely be more compact and faster than a float method and probably the itoa method as well.
Yup, I find in this forum in particular, sometimes the best solution is often ignored/brushed off for some reason.
Someone will post a solution which is perfectly adequate, but another member will post something arguably worse afterwards and that will take the thread/OP on a completely unnecessary tangent.
I guess that's why different platforms (stackoverflow/reddit) have a rating system.