43oh

# Converting Float to String

## Recommended Posts

char final;

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!

##### Share on other sites

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 = '.';
final = '\0';
```

Of course, this looks a bit messy and less comprehensible, so I understand you don't want to go there.

##### Share on other sites

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.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
• Blog

• #### Activity

×
• Create New...