Display float value w/o scientific notation
sprintf('%f',$ret)
doesn't work, it returns0.000000
. Overflow?
sprintf
works, however you miss some point here.
0.000000
is not overflow. It's just that sprintf
for the %f
modifier uses 6 digits per default. Also please take care that %f
is locale aware, %F
is probably better suited.
You might want to use more digits, e.g. let's say 4 000 000 (four million):
$ php -r "printf('%.4000000F', 1*0.000000001);"
Notice: printf(): Requested precision of 4000000 digits was truncated to PHP maximum of 53 digits in Command line code on line 1
Call Stack:
0.0001 319080 1. {main}() Command line code:0
0.0001 319200 2. printf() Command line code:1
0.00000000100000000000000006228159145777985641889706869
As this example shows, there is not only a common value (6 digits) but also a maximum (probably depended on the computer system PHP executes on), here truncated to 53 digits in my case as the warning shows.
Because of your question I'd say you want to display:
0.000000001
Which are nine digits, so you need to write it that way:
sprintf('%.9F',$ret)
However, you might want to do this:
rtrim(sprintf('%.20F', $ret), '0');
which will remove zeroes from the right afterwards:
0.000000001
Hope this is helpful.
how to prevent float variables displaying as scientific notation when printing
This is the scientific notation of float number. So, if you want to format then you should use number_format() function.
Below example the second parameter will tell at what precision do you need.
So, as per your example you should use 14.
Try this:
$var = number_format((float)-0.00000025478625, 14);
print($var);
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 to print float as string in Golang without scientific notation
The package doc of fmt
explains it: The %v
verb is the default format, which for floating numbers means / reverts to %g
which is
%e for large exponents, %f otherwise. Precision is discussed below.
If you always want "decimal point but no exponent, e.g. 123.456", use %f
explicitly.
But you can only use that for floating numbers, so you have to check the type of the value you print. For that you may use a type switch or type assertion.
Example:
switch v.(type) {
case float64, float32:
fmt.Printf("%f\n", v)
default:
fmt.Printf("%v\n", v)
}
Output (try it on the Go Playground):
mydata
1234567890.123000
How do I print a double value without scientific notation using Java?
You could use printf()
with %f
:
double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);
This will print dexp: 12345678.000000
. If you don't want the fractional part, use
System.out.printf("dexp: %.0f\n", dexp);
0 in %.0f
means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this %.8f
. By default fractional part is printed up to 6 decimal places.
This uses the format specifier language explained in the documentation.
The default toString()
format used in your original code is spelled out here.
How to suppress scientific notation when printing float values?
'%f' % (x/y)
but you need to manage precision yourself. e.g.,
'%f' % (1/10**8)
will display zeros only.
details are in the docs
Or for Python 3 the equivalent old formatting or the newer style formatting
Formatting A Double In A String Without Scientific Notation
Use just %f
instead of %.0f
.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double foo = 123456789.1234;
String str = String.format("%f", foo);
System.out.println(str);
// If you want to get rid of the trailing zeros
str = new BigDecimal(str).stripTrailingZeros().toString();
System.out.println(str);
}
}
Output:
123456789.123400
123456789.1234
Related Topics
Custom User Authentication Base on the Response of an API Call
What's the Best Way to Pass a PHP Variable to JavaScript
Will Copy-On-Write Prevent Data Duplication on Arrays
PHP Messing with HTML Charset Encoding
Ssl Operation Failed with Code 1: Dh Key Too Small
PHP Emitting 500 on Errors - Where Is This Documented
MySQL Db Question Marks Instead of Hebrew Characters..
Regex Backreference to Match Different Values
How to Capture the Result of Var_Dump to a String
How Do Detect That Transaction Has Already Been Started
How to Extract Images from a PDF File
Access Get Directly from JavaScript
PHP Date() and Strtotime() Return Wrong Months on 31St