It looks like %f works just fine:
#include <stdio.h>
int main()
{
double d = 5000683;
printf("%f\n", d);
printf("%.0f\n", d);
return 0;
}
The output of this code will be
5000683.000000
5000683
The second printf() statement sets the precision to 0 (by prefixing f with .0) to avoid any digits after the decimal point.
Use std::fixed stream manipulator:
cout<<fixed<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;
As mentioned above, you can use std::fixed to solve your problem, like this:
cout << fixed;
cout << "Bas ana: " << x << "\tSon faiz: " << t << "\tSon ana: " << x+t <<endl;
However, after you've done this, every time you print a float or a double anywhere in your project, the number will still be printed in this fixed notation. You could turn it back by using
cout << scientific;
but this might become tedious if your code gets more complicated.
This is why Boost made the I/O Stream State Saver, which automatically returns the I/O stream you're using to the state it was before your function call. You can use it like this:
#include <boost/io/ios_state.hpp> // you need to download these headers first
{
boost::io::ios_flags_saver ifs( os );
cout << ios::fixed;
cout<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;
} // at this bracket, when ifs goes "out of scope", your stream is reset
You can find more info about Boost's I/O Stream State Saver in the official docs.
You may also want to check out the Boost Format library which can also make your outputting easier, especially if you have to deal with internationalisation. However, it won't help you for this particular problem.
How do I print a double value without scientific notation using Java? - Stack Overflow
How to print the char, integer, float and double values without using format specifiers in c - Stack Overflow
c - Printing a double without the decimal places - Stack Overflow
How can I get cout to print large numbers that aren't in scientific notation in C++?
As mentioned in the comments of the other answer, your decimal floating point numbers are stored as binary and rarely have finite representations.
If you simply want code that passes your test I would mention that it is much easier to remove padding from std::fixed than it is to expand the scientific notation.
#include <iostream>
#include <string>
#include <sstream>
#include <limits>
#include <iomanip>
#include <cstdlib>
#include <cassert>
#include <cstddef>
static std::string to_string(double d)
{
std::ostringstream oss;
oss.precision(std::numeric_limits<double>::digits10);
oss << std::fixed << d;
std::string str = oss.str();
// Remove padding
// This must be done in two steps because of numbers like 700.00
std::size_t pos1 = str.find_last_not_of("0");
if(pos1 != std::string::npos)
str.erase(pos1+1);
std::size_t pos2 = str.find_last_not_of(".");
if(pos2 != std::string::npos)
str.erase(pos2+1);
return str;
}
static void test_string_conversion(const std::string& str)
{
assert( to_string( atof(str.c_str()) ) == str );
}
int main(void)
{
test_string_conversion( "1.5203" );
test_string_conversion( "-1.025" );
test_string_conversion( "3.1415" );
test_string_conversion( "-38271" );
test_string_conversion( "0.8382" );
test_string_conversion( "-0.8382" );
test_string_conversion( "7" );
test_string_conversion( "-3" );
test_string_conversion( "0.0000024" );
test_string_conversion( "7300000000" );
}
What you are looking for is std::fixed
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::fixed << 1.5203 << "\n";
std::cout << std::fixed << -1.025 << "\n";
std::cout << std::fixed << 3.1415 << "\n";
std::cout << std::fixed << -38271 << "\n";
std::cout << std::fixed << 0.8382 << "\n";
std::cout << std::fixed << -0.8382 << "\n";
std::cout << std::fixed << 7 << "\n";
std::cout << std::fixed << -3 << "\n";
std::cout << std::fixed << 0.0000024 << "\n";
std::cout << std::fixed << 7300000000 << "\n";
}
1.520300
-1.025000
3.141500
-38271
0.838200
-0.838200
7
-3
0.000002
7300000000
Java prevent E notation in a double:
Five different ways to convert a double to a normal number:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
This program prints:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
Which are all the same value.
Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?
http://youtube.com/watch?v=PZRI1IfStY0
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.
To print a char, use:
fputc(c, stream)
(If the stream is stdout, you can use putchar(c).)
To print an int:
- If the
intis negative, print “-”. - Calculate the individual digits of the integer. This can be done either by calculating the digits from least significant to most significant and saving them in a buffer to be printed in reverse order or by figuring out where the most significant digit is and then calculating the digits from most significant to least significant. You can use a remainder operation, such as
x % 10, to calculate the least significant digit of a number, and you can use division, such asx / 10, to remove that digit. - One caveat is that, if the original number is negative, you have to be careful about calculating its digits. The
%operator will return negative values. Some people attempt to deal with this by negating the integer if it is negative. However, if the number is the least possibleint, this may overflow. E.g., in many C implementations, the leastintvalue is -2,147,483,648, but it cannot be negated because the greatestintis 2,147,483,647. - Any digit in numeric form (0 to 10) can be converted to a character (“0” to “9”) by adding
'0', such asint d = x % 10; char c = d + '0';. The C standard guarantees that this produces the appropriate character inc. - After you obtain the characters from the digits, print them.
To print a float or double:
- Doing this completely correctly is hard, although it is a solved problem. The classic reference for it is Correctly Rounded Binary-Decimal and Decimal-Binary Conversions by David M. Gay.
- If you just want a simple implementation suitable for a learning exercise, then you can format a floating-point value much as you would an integer: Calculate the digits individually. You also need to decide whether to print a fixed-point notation or a scientific notation (or other).
- To print a fixed-point notation, print the integer part of the value as above, for integer types. Then print a “.” and some digits for the fractional part of the value.
- To print a scientific notation, calculate the value of the exponent part (e.g., to express 12345789 as “1.23456789e7”, the exponent is 7, for 107. Divide the value by 10 raised to the power of that exponent and print the resulting value as a fixed-point number (so, in this example, you print “1.23456789”), then print “e”, the print the exponent part.
- Floating-point rounding errors will occur in the above, making it suitable only for a learning exercise, not for use in a quality product.
The above should suffice to get you started. It is not complete code, obviously.
just one thought, not very optimal:
int myvalue = 12345;
char buffer[100];
size_t index = 0;
while (myvalue) {
buffer[index] = '0' + myvalue % 10;
myvalue = myvalue / 10;
index++;
}
buffer[index] = '\0';
reverse(buffer);
fprintf(stdout, buffer);
you have to consider the negative sign. And the sizeof buffer (100 is a very bad guess).
try
printf("%.0lf\n",phoneNum);
you may also prefer
long long phoneNum;
phoneNum = strtoll(buffer,NULL,0);
printf("%lld\n",phoneNum);
instead. Depending on the system, though, you may need other function to convert (I think it's _strtoui64 for windows).
Use %0.0lf or go with an integer
Lookup format specs for printf
I've written a program that prints out numbers in an arithmetic series, and once the numbers start to get into the millions or larger the numbers are printed in scientific notation. (example: 1346269 is written as 1.34627e+006)
Is there some way that I can get the program to print it without the scientific notation? I've got the variables printed declared using double.
Use snprintf to print to a temporary buffer then remove the trailing '0' characters manually. There is no other way that's both correct and reasonably easy to implement.
Try:
printf("%.20g\n", 1000000.0); // = 1000000
This will switch to scientific notation after 20 significant digits (default is after 6 digits for "%g"):
printf("%.20g\n", 1e+19); // = 10000000000000000000
printf("%.20g\n", 1e+20); // = 1e+20
But be careful with double precision:
printf("%.20g\n", 0.12345); // = 0.12345000000000000417
printf("%.15g\n", 0.12345); // = 0.12345
Java prevent E notation in a double:
Five different ways to convert a double to a normal number:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
This program prints:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
Which are all the same value.
Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?
http://youtube.com/watch?v=PZRI1IfStY0
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.
What am I doing wrong?
Several things:
- Use
%.10eformat for scientific notation withprintffor a printout with ten digits after the dot, - Return an
intfrom yourmain, - Consider not using
publicto name a variable, on the chance that your program would need to be ported to C++, wherepublicis a keyword.
Here is how you can fix your program:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(){
double p;
double a = 16;
double b = 54;
p = (pow(a,b));
printf("%.10e\n", p);
return 0;
}
Demo on ideone.
Have you tried:
printf("%e\n", public);
The %e specifier is for scientific notation, as described in the documentation
So, I'm thinking that what you really want is just the ability to print it without scientific notation. If you're using printf, what you want is:
printf( "%f1000.0", value );
// note that 1000 is way larger than need be,
// I'm just too lazy to count the digits
With cout, try something like:
cout.setf(ios::fixed);
cout << setprecision(0) << value;
If you want to print it as a power of two (2^1000 vs 10715...), you're on your own.
There is a practical limit to how large a number that can be directly manipulated in machine registers can be. if you are using double precision floats there are a total of 64 bits, some of which are devoted to the mantissa, some to the exponent, and 1 to the sign bit.
2^1000 needs a 1001 bit integer to be represented without losing precision. In order to work with numbers like that you will need to use a library that has big number support, such as GNU MP.
For a general-purpose¹ solution you need to preserve 339 places:
doubleValue.ToString("0." + new string('#', 339))
The maximum number of non-zero decimal digits is 16. 15 are on the right side of the decimal point. The exponent can move those 15 digits a maximum of 324 places to the right. (See the range and precision.)
It works for double.Epsilon, double.MinValue, double.MaxValue, and anything in between.
The performance will be much greater than the regex/string manipulation solutions since all formatting and string work is done in one pass by unmanaged CLR code. Also, the code is much simpler to prove correct.
For ease of use and even better performance, make it a constant:
public static class FormatStrings
{
public const string DoubleFixedPoint = "0.###################################################################################################################################################################################################################################################################################################################################################";
}
¹ Update: I mistakenly said that this was also a lossless solution. In fact it is not, since ToString does its normal display rounding for all formats except r. Live example. Thanks, @Loathing! Please see Lothing’s answer if you need the ability to roundtrip in fixed point notation (i.e, if you’re using .ToString("r") today).
I had a similar problem and this worked for me:
doubleValue.ToString("F99").TrimEnd('0')
F99 may be overkill, but you get the idea.