xyiii 0 Posted February 20, 2015 Share Posted February 20, 2015 char final[6]; sprintf(final, "%.3f",current); Serial.println(final); When I put this code to calculate it prints only the "%.3f" I know floating point is not good to use for MSP430, but I do need the decimal places for my calculated results and need to convert to string pass on java socket. Or Can someone introduce me the fixed point calculation? many thanks! Quote Link to post Share on other sites
roadrunner84 466 Posted February 23, 2015 Share Posted February 23, 2015 You can split your displaying in two integers, in this example I assume current is an electrical current in mA (so displaying is in resolution up to uA, since you have three decimal places right of the dot) Instead of calculating something to map to mA, map it to uA: unsigned int rawADC = getADC(); // rawADC is retrieved from some ADC value float current = rawADC * 0.123 + 456.0; // this is some dummy scaling calculation unsigned int rawADC = getADC(); unsigned long current = rawADC * 123 + 456000; You see, the same information is contained, but without using float. Now for converting it to a string, first using sprintf: sprintf(final, "%u.%03u", current / 1000, current % 1000); You see, the same information is now contained in final, but without floating points. A few optimisations can be placed in here; use itoa() instead of sprintf(), use div() instead of / and % : ldiv_t fraction = ldiv(current, 1000); itoa(fraction.quot, final, 10); fraction.rem += 1000; itoa(fraction.rem, final + 3, 10); final[3] = '.'; final[7] = '\0'; Of course, this looks a bit messy and less comprehensible, so I understand you don't want to go there. xyiii 1 Quote Link to post Share on other sites
enl 227 Posted February 23, 2015 Share Posted February 23, 2015 A few questions: What is the value representing? What range does the whole number part take?? Do you need to store more precision than the three digits after the decimal for any reason, or only those three? What RESOLUTION do you need? (0.001? 0.005? other?) Options, depending on the details, roeadrunner84's solution, where you maintain the float until the string generation, using the TI fixed point library for all of it, or doing the fixed point yourself using integers. For me to make a decision, I would need to know more detail, but my default would be the TI fixed point lib instead of float throughout the application, if possible, as it is faster than float, and likely smaller to build. Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.