S
S
SVM122015-12-30 11:51:25
C++ / C#
SVM12, 2015-12-30 11:51:25

How to properly format float to string?

The task is to convert a float to a string with rounding and with a given precision,
for example 2:
2.150000->2.15
2.000000->2
2.004000->2
2.005000->2.01
1140.000000->1140 Using
standard means with printf:
%.2f is always a fixed number (2 ) decimal places - not suitable
%.2g - seems to be suitable, but sometimes numbers with epsilon appear, for example, instead of 1140 -> 1.1e+02

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Armenian Radio, 2015-12-30
@gbg

Tell the whole problem. Perhaps you are trying to use floating point numbers where fixed point numbers are needed.

S
SVM12, 2015-12-30
@SVM12

This is the quantity field. It may be fractional. On a mobile device, due to the small screen, I want integers to be shown without a part after the decimal point. It is also assumed that the maximum number of numbers after the decimal point will be 2. But, if suddenly this number increases in the future, then we would like rounding to occur.

T
to_climb, 2015-12-30
@to_climb

Maybe %g isn't really that good, see the description .
Exponential notation should only happen when the number is less than 10^-2 (with %.2g rounding precision).
Those. if you check that the number is certainly greater than 0.01, then you can use it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question