Convert float to String and String to float in Java
Using Java’s Float
class.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)
How to simply convert a float to a string in c?
The second parameter is the format string after which the format arguments follow:
fprintf(fPointer, "%f", amount);
%f
tells fprintf
to write this argument (amount
) as string representation of the float value.
A list of possible format specifiers can (for example) be found here.
Convert float to std::string in C++
Unless you're worried about performance, use string streams:
#include <sstream>
//..
std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());
If you're okay with Boost, lexical_cast<> is a convenient alternative:
std::string s = boost::lexical_cast<std::string>(myFloat);
Efficient alternatives are e.g. FastFormat or simply the C-style functions.
Convert float to string with at least one decimal place (javascript)
If you want to append .0
to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it specially.
function toNumberString(num) {
if (Number.isInteger(num)) {
return num + ".0"
} else {
return num.toString();
}
}
Input Output
3 "3.0"
3.4567 "3.4567"
Convert float to string in positional format (without scientific notation and false precision)
Unfortunately it seems that not even the new-style formatting with float.__format__
supports this. The default formatting of float
s is the same as with repr
; and with f
flag there are 6 fractional digits by default:
>>> format(0.0000000005, 'f')
'0.000000'
However there is a hack to get the desired result - not the fastest one, but relatively simple:
- first the float is converted to a string using
str()
orrepr()
- then a new
Decimal
instance is created from that string. Decimal.__format__
supportsf
flag which gives the desired result, and, unlikefloat
s it prints the actual precision instead of default precision.
Thus we can make a simple utility function float_to_str
:
import decimal
# create a new context for this task
ctx = decimal.Context()
# 20 digits should be enough for everyone :D
ctx.prec = 20
def float_to_str(f):
"""
Convert the given float to a string,
without resorting to scientific notation
"""
d1 = ctx.create_decimal(repr(f))
return format(d1, 'f')
Care must be taken to not use the global decimal context, so a new context is constructed for this function. This is the fastest way; another way would be to use decimal.local_context
but it would be slower, creating a new thread-local context and a context manager for each conversion.
This function now returns the string with all possible digits from mantissa, rounded to the shortest equivalent representation:
>>> float_to_str(0.1)
'0.1'
>>> float_to_str(0.00000005)
'0.00000005'
>>> float_to_str(420000000000000000.0)
'420000000000000000'
>>> float_to_str(0.000000000123123123123123123123)
'0.00000000012312312312312313'
The last result is rounded at the last digit
As @Karin noted, float_to_str(420000000000000000.0)
does not strictly match the format expected; it returns 420000000000000000
without trailing .0
.
How can I convert a float to string?
Sometimes, the answer is easy: to_string()
.
let pi = 3.1415926;
let s = pi.to_string(); // : String
Background
The foundation for "creating a readable string representation of something" is in the fmt
module. Probably the most important trait in this module is Display
. Display
is an abstraction over types that can be formatted as a user-facing string (pretty much exactly what you want). Usually the Display
trait is used by println!()
and friends. So you can already convert your float to string with the format!()
macro:
let s = format!("{}", pi);
But there is something else: the ToString
trait. This trait talks about types that can be converted to a String
. And now, there is a magic implementation:
impl<T> ToString for T
where T: Display + ?Sized
This means: every type which implements Display
also automatically implements ToString
! So instead of writing format!("{}", your_value)
you can simply write your_value.to_string()
!
While these wildcard implementations are extremely useful and versatile, they have one disadvantage: finding methods is much harder. As you point out, the documentation of f32
doesn't mention to_string()
at all. This is not very good, but it is a known issue. We're trying to improve this situation!
Advanced formatting
The to_string()
method uses the default formatting options, so it's equivalent to format!("{}", my_value)
. But sometimes, you want to tweak how the value is converted into a string. To do that, you have to use format!()
and the full power of the fmt
format specifier. You can read about those in the module documentation
. One example:
let s = format!("{:.2}", pi);
This will result in a string with exactly two digits after the decimal point ("3.14"
).
If you want to convert your float into a string using scientific notation, you can use the {:e}
(or {:E}
) format specifier which corresponds to the LowerExp
(or UpperExp
) trait.
let s = format!("{:e}", pi * 1_000_000.0);
This will result in "3.1415926e6"
.
Convert float to string without sprintf()
Try this. It should be nice and small. I've output the string directly - doing a printf, rather than a sprintf. I'll leave it to you to allocate space for the return string, as well as copying the result into it.
// prints a number with 2 digits following the decimal place
// creates the string backwards, before printing it character-by-character from
// the end to the start
//
// Usage: myPrintf(270.458)
// Output: 270.45
void myPrintf(float fVal)
{
char result[100];
int dVal, dec, i;
fVal += 0.005; // added after a comment from Matt McNabb, see below.
dVal = fVal;
dec = (int)(fVal * 100) % 100;
memset(result, 0, 100);
result[0] = (dec % 10) + '0';
result[1] = (dec / 10) + '0';
result[2] = '.';
i = 3;
while (dVal > 0)
{
result[i] = (dVal % 10) + '0';
dVal /= 10;
i++;
}
for (i=strlen(result)-1; i>=0; i--)
putc(result[i], stdout);
}
Related Topics
C and C++ Programming on Ubuntu 11.10
Number of Combinations (N Choose R) in C++
Measure Execution Time in C++ Openmp Code
Round a Float to a Regular Grid of Predefined Points
Linux Allocator Does Not Release Small Chunks of Memory
Multithreaded Rendering on Opengl
How to Recover View Space Position Given View Space Depth Value and Ndc Xy
Call to Pure Virtual Function from Base Class Constructor
How to Programmatically Gain Root Privileges
How to Define a Template Function Within a Template Class Outside of the Class Definition
Sendinput() Not Equal to Pressing Key Manually on Keyboard in C++
Convert Std::Bind to Function Pointer