Is there a direct function to set the decimal of number. For example I got 3.14341
and my parameter is 2, so I get 3.14. There is a function setprecision but it only prints the result. Also, I made an algorithm like this:
std::string fixPrecision(std::string const& value, int digits)
{
std::string num = value;
float temp = std::stof(num);
float fractpart, intpart;
fractpart = modf(temp, &intpart);
int a = (int)(fractpart * pow(10,digits));
double last = intpart + a*(pow(0.1 , digits));
return std::to_string(last);
}
It works well. I get what I want but I have to convert it to string so the result is 123.120000 instead of 123.12.
I could sure use some help here. Thanks in advance.
Edit: It is not a duplicate question because my function needs to take integer and return numbers with string format. Thanks again.
Fool of me. The answer is as simple as this. I did a lot of things needlessly...
std::string fixPrecision(std::string const& value, int digits)
{
auto pos = value.find(".");
if(pos != std::string::npos)
return value.substr(0, pos+digits+1);
return value;
}
not exactly, but you can set the precision using std::setprecision
define a method:
void printWithPrecision(const double value, unsigned decimalPlaces)
{
std::cout << "A Double with " << decimalPlaces <<" decimal places: "<<std::setprecision(decimalPlaces) << value << std::endl;
}
and call it like:
double d = 7987.12354689765416;
for (auto x = 0; x<10; x++)
{
printWithPrecision(d, x);
}
dont forget to include the input-output-manipulator:
#include <iomanip>
Related
I want to ask how to remove trailing zeros after decimal point?
I've read lots of topics about it but I don't understand them clearly. Could you show me any easy understanding ways ?
For example 12.50 to 12.5, but the actual output is 12.50
This is one thing that IMHO is overly complicated in C++. Anyway, you need to specify the desired format by setting properties on the output stream. For convenience a number of manipulators are defined.
In this case, you need to set fixed representation and set precision to 2 to obtain the rounding to 2 decimals after the point using the corresponding manipulators, see below (notice that setprecisioncauses rounding to the desired precision). The tricky part is then to remove trailing zeroes. As far as I know C++ does not support this out of the box, so you have to do some string manipulation.
To be able to do this, we will first "print" the value to a string and then manipulate that string before printing it:
#include <iostream>
#include <iomanip>
int main()
{
double value = 12.498;
// Print value to a string
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
std::string str = ss.str();
// Ensure that there is a decimal point somewhere (there should be)
if(str.find('.') != std::string::npos)
{
// Remove trailing zeroes
str = str.substr(0, str.find_last_not_of('0')+1);
// If the decimal point is now the last character, remove that as well
if(str.find('.') == str.size()-1)
{
str = str.substr(0, str.size()-1);
}
}
std::cout << str << std::endl;
}
For C++ check this How to output float to cout without scientific notation or trailing zeros?
using printf() you may use following method to do this,
int main()
{
double value = 12.500;
printf("%.6g", value ); // 12.5 with 6 digit precision
printf("%.6g", 32.1234); // 32.1234
printf("%.6g", 32.12300000); // 32.123
}
std::string example = std::to_string(10.500f);
while (example[example.size() - 1] == '0' || example[example.size() - 1] == '.')
example.resize(example.size() - 1);
Just use 'printf' function.
printf("%.8g",8.230400); will print '8.2304'
float value =4.5300;
printf ("%.8g",value);
will return 4.53.
Try this code . It is quite simple.
I was stumped by this for a while and didn't want to convert to a string to get the job done, so I came up with this:
float value = 1.00;
char buffer[10];
sprintf(buffer, "%.2f", value);
int lastZero = strlen(buffer);
for (int i = strlen(buffer) - 1; i >= 0; i--)
{
if (buffer[i] == '\0' || buffer[i]=='0' || buffer[i]=='.')
lastZero = i;
else
break;
}
if (lastZero==0)
lastZero++;
char newValue[lastZero + 1];
strncpy(newValue, buffer, lastZero);
newValue[lastZero] = '\0';
newValue = 1
you can round-off the value to 2 digits after decimal,
x = floor((x * 100) + 0.5)/100;
and then print using printf to truncate any trailing zeros..
printf("%g", x);
example:
double x = 25.528;
x = floor((x * 100) + 0.5)/100;
printf("%g", x);
output: 25.53
i know to reverse the digits of a number(integer) in c but my questions is how can we reverse the digits of a real no
for e.g 1200.23 gets reversed as 32.0021
code for integers
#include <stdio.h>
/* Iterative function to reverse digits of num(integer)*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
Obviously your paramater needs to be floating point type.
You could convert double to string then reverse the string then convert back to double:
#include <string>
#include <sstream>
template<typename T>
std::string toString(T t)
{
std::stringstream ss;
ss << t;
rteurn ss.str();
}
double reversDigits(double num)
{
std::string s = std::to_string(num);
std::reverse(s.begin(), s.end());
double d;
std::stringstream ss(s);
ss >> d;
return d;
}
You could use the following code, where the iostream library is being used:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
double pass = 0;
double n;
double result=0;
cout << "Please enter a number to reverse" << endl;
cin >> n;
while (trunc(n / pow(10.0, pass)) > 0) {
result = fmod((n / pow(10.0, pass)), 10.0);
cout << trunc(result);
pass = pass + 1;
}
cout << endl;
system("pause");
return 0;
}
This uses the methods (12345/10), which gives you 1234.5 which then truncates into 1234. The above code also use the modulo method ('%' is the operator for modulo). For example, if you do 12345 % 10, the program displays the remainder of 12345/10, which in this case, would be 5.
I used this method in a loop to get the desired output.
PLEASE NOTE THAT I MADE THIS PROGRAM FOR A CLASS, SO IF THIS IS NOT EXACTLY WHAT YOU ARE LOOKING FOR, KINDLY DISREGARD THIS POST.
Try this code-
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
float reversDigits(float num)
{
char buffer[20],ch,*ptr;
int i,j,len;
snprintf(buffer,20,"%.3lf",num);
len = strlen(buffer);
for(i=0,j=len-1;i<j;i++,j--)
{
ch=buffer[i];
buffer[i]=buffer[j];
buffer[j]=ch;
}
buffer[len] = '\0';
return atof(buffer);
}
int main()
{
float num = 45000.062;
printf("Reverse of no. is %.5lf\n", reversDigits(num));
return 0;
}
Am passing a number with 3 digits after ., so i am using %.3lf in snprintf, if you simply use %lf means, while converting it to string it will add zeros and some numbers. To avoid that am using, else you need to do a little bit of more work to remove it!
Note: while converting string to float else float to string, in decimal position it will add some extra number or zero. The programmer need to take care of it!
This question already has answers here:
C++ setprecision(2) printing one decimal?
(2 answers)
Closed 8 years ago.
I want to know how I can, in c++, print for example 10 as 10.0000, or 10.1 as 10.1000.
I want the total number of digits to be the same and pad with '0' the empty spaces on the right.
I read about 'setprecision', but it doesn't add '0'.
'fixed' is the numbers of digits after the floating point, and I want the total number of digits to be fixed.
is there a way to do this, not using printf?
You can do something like this: (considering you want a fixed length of 5)
int precision(double num){
int p;
if (num <1)
p = 5;
else if (num <10)
p = 4;
else if (num <100)
p = 3;
else if (num <1000)
p = 2;
else if (num <10000)
p = 1;
else
p = 0;
return p;
}
int main(){
double num;
std::cin>>num;
std::cout <<std::fixed <<std::setprecision(precision(num)) << num <<std::endl;
return 0;
}
As you required, if the number of digits After decimal is more than 5 it will be truncated.
Now, implement your own logic for what you want to do if number of digits Before decimal point is more than 5. :)
You will ultimately need to find out the length in digits of the double. I'm not entirely sure how to go about that in a safe way but fortunately I can show you an example where we can do this with integers.
Basically I would recommend creating a new facet class that implements the custom formatting inside do_put(). Then imbue this class into your stream. The exact same thing as below can be done for the overload of do_put() that takes a double as its last argument, plus a few changes to the for loop.
#include <iostream>
#include <iomanip>
class num_put : public std::num_put<char>
{
iter_type do_put( iter_type out, std::ios_base& str, char, long v ) const
{
std::streamsize width = str.width();
int digits = num_digits(v);
if (digits > width)
for (std::streamsize i(0); i < digits - width; ++i)
v /= 10;
/* v = static_cast<int>(v * 10) / 10.; // use this instead for
*/ // floating-point
str.flags(std::ios_base::left);
out = std::num_put<char>::do_put(out, str, '0', v);
str.width(width);
return out;
}
private:
template<class T>
static int num_digits(T num) // only works for integral types
{
int length = 1;
while (num /= 10)
++length;
return length;
}
};
int main()
{
std::cout.imbue(std::locale(std::cout.getloc(), new num_put));
std::cout << std::setw(5) << 123; // 12300
std::cout << std::setw(5) << 123456789; // 12345
}
I needed to convert a fractional part of a number into integer without a comma,
for example I have 3.35 I want to get just 35 part without zero or a comma,
Because I used the modf() function to extract the the fractional part but it gives me a 0.35
if there is any way to do that or to filter the '0.' part I will be very grateful if you show me how with the smaller code possible,
A bit more efficient than converting to a string and back again:
int fractional_part_as_int(double number, int number_of_decimal_places) {
double dummy;
double frac = modf(number,&dummy);
return round(frac*pow(10,number_of_decimal_places));
}
#include <iostream>
#include <cmath>
double round(double r) {
return (r > 0.0) ? std::floor(r + 0.5) : std::ceil(r - 0.5);
}
double floor_to_zero(double f) {
return (f > 0.0) ? std::floor(f) : std::ceil(f);
}
double sign(double s) {
return (s < 0.0) ? -1.0 : 1.0;
}
int frac(double f, int prec) {
return round((f - floor_to_zero(f)) * prec) * sign(f);
}
int main() {
double a = 1.2345;
double b = -34.567;
std::cout << frac(a, 100) << " " << frac(b, 100) << std::endl; // 23 57
}
another solution
int precision= 100;
double number = 3.35;
int f = floor(xx);
double temp = ( f - number ) * -1;
int fractional_part = temp * precision;
IF you need it as a string, a quite easy C style solution would be (should work for variable number of decimal places):
double yourNumber = 0.35f;
char buffer[32];
snprintf(buffer, 32, "%g", yourNumber);
strtok(buffer, "."); // Here we would get the part before . , should still check
char* fraction = strtok(NULL, ".");
int fractionAsInt = atoi(fraction);
This example lacks error handling in case of a bad string and is not feasible if you just need a fixed number of decimal places, since the arithmetic approaches work better there.
Something like this should work:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static int get_frac(double value, unsigned short precision)
{
return (int)((value - (long)value) * pow(10, precision));
}
static int get_frac_no_trailing_zeros(double value, unsigned short precision)
{
int v = get_frac(value, precision);
while (v % 10 == 0)
v /= 10;
return v;
}
int main(int argc, char *argv[])
{
double v;
v = 123.4564;
printf("%.4f = %d\n", v, get_frac(v, 2));
printf("%.4f = %d\n", v, get_frac(v, 4));
printf("%.4f = %d\n", v, get_frac(v, 6));
printf("%.4f = %d\n", v, get_frac_no_trailing_zeros(v, 6));
return EXIT_SUCCESS;
}
You may also want to either avoid calling pow by having a user supply a number in a power of 10 in a first place, or use a lookup table.
Using some stl magic, here is the sample code:
typedef std::pair<int, int> SplitFloat;
SplitFloat Split(float value, int precision)
{
// Get integer part.
float left = std::floor(value);
// Get decimal part.
float right = (value - left) * float(std::pow(10, precision));
return SplitFloat(left, right);
}
It can be improved, but is pretty straightforward.
I just did something close to what you are trying to do, though I'm still pretty new. None the less, maybe this will help someone in the future as I landed here looking for results for my problem.
The first step is making sure that the variable that contains 3.35 is a double, but that's probably obvious.
Next, create a variable that is only an integer and set it's value equal to the value of the double. It will then only contain the whole number.
Then subtract the whole number (int) from the double. You will be left with the fraction/decimal value. From there, just multiply by 100.
Beyond the 100ths decimal value, you would have to do a little more configuring obviously, but it should be fairly simple to do with an if statement. If the decimal value is greater than .99, multiply 1000 instead etc..
Here's how I would do it.
#include <sstream>
#include <string>
int main()
{
double d = yourDesiredNumber; //this is your number
std::ostringstream out;
out << setprecision(yourDesiredPrecision) << std::fixed
<< std::showpoint << d;
std::istringstream in(out.str());
std::string wholePart; //you won't need this.
int fractionalPart;
std::getline(in, wholePart, '.');
in >> fractionalPart;
//now fractionalPart contains your desired value.
}
I'm pretty sure that instead of two different istringstream and ostringstream objects you could have gotten away with just one stringstream object, but I am not sure about the details (never used that class) so I didn't use it in the example.
What are the different techniques used to convert float type of data to integer in C++?
#include <iostream>
using namespace std;
struct database {
int id, age;
float salary;
};
int main() {
struct database employee;
employee.id = 1;
employee.age = 23;
employee.salary = 45678.90;
/*
How can i print this value as an integer
(with out changing the salary data type in the declaration part) ?
*/
cout << endl << employee.id << endl << employee.
age << endl << employee.salary << endl;
return 0;
}
What you are looking for is 'type casting'. typecasting (putting the type you know you want in brackets) tells the compiler you know what you are doing and are cool with it. The old way that is inherited from C is as follows.
float var_a = 9.99;
int var_b = (int)var_a;
If you had only tried to write
int var_b = var_a;
You would have got a warning that you can't implicitly (automatically) convert a float to an int, as you lose the decimal.
This is referred to as the old way as C++ offers a superior alternative, 'static cast'; this provides a much safer way of converting from one type to another. The equivalent method would be (and the way you should do it)
float var_x = 9.99;
int var_y = static_cast<int>(var_x);
This method may look a bit more long winded, but it provides much better handling for situations such as accidentally requesting a 'static cast' on a type that cannot be converted. For more information on the why you should be using static cast, see this question.
Normal way is to:
float f = 3.4;
int n = static_cast<int>(f);
Size of some float types may exceed the size of int.
This example shows a safe conversion of any float type to int using the int safeFloatToInt(const FloatType &num); function:
#include <iostream>
#include <limits>
using namespace std;
template <class FloatType>
int safeFloatToInt(const FloatType &num) {
//check if float fits into integer
if ( numeric_limits<int>::digits < numeric_limits<FloatType>::digits) {
// check if float is smaller than max int
if( (num < static_cast<FloatType>( numeric_limits<int>::max())) &&
(num > static_cast<FloatType>( numeric_limits<int>::min())) ) {
return static_cast<int>(num); //safe to cast
} else {
cerr << "Unsafe conversion of value:" << num << endl;
//NaN is not defined for int return the largest int value
return numeric_limits<int>::max();
}
} else {
//It is safe to cast
return static_cast<int>(num);
}
}
int main(){
double a=2251799813685240.0;
float b=43.0;
double c=23333.0;
//unsafe cast
cout << safeFloatToInt(a) << endl;
cout << safeFloatToInt(b) << endl;
cout << safeFloatToInt(c) << endl;
return 0;
}
Result:
Unsafe conversion of value:2.2518e+15
2147483647
43
23333
For most cases (long for floats, long long for double and long double):
long a{ std::lround(1.5f) }; //2l
long long b{ std::llround(std::floor(1.5)) }; //1ll
Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.
I believe you can do this using a cast:
float f_val = 3.6f;
int i_val = (int) f_val;
the easiest technique is to just assign float to int, for example:
int i;
float f;
f = 34.0098;
i = f;
this will truncate everything behind floating point or you can round your float number before.
One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.
int someint = (somedouble+epsilon);
This is one way to convert IEEE 754 float to 32-bit integer if you can't use floating point operations. It has also a scaler functionality to include more digits to the result. Useful values for scaler are 1, 10 and 100.
#define EXPONENT_LENGTH 8
#define MANTISSA_LENGTH 23
// to convert float to int without floating point operations
int ownFloatToInt(int floatBits, int scaler) {
int sign = (floatBits >> (EXPONENT_LENGTH + MANTISSA_LENGTH)) & 1;
int exponent = (floatBits >> MANTISSA_LENGTH) & ((1 << EXPONENT_LENGTH) - 1);
int mantissa = (floatBits & ((1 << MANTISSA_LENGTH) - 1)) | (1 << MANTISSA_LENGTH);
int result = mantissa * scaler; // possible overflow
exponent -= ((1 << (EXPONENT_LENGTH - 1)) - 1); // exponent bias
exponent -= MANTISSA_LENGTH; // modify exponent for shifting the mantissa
if (exponent <= -(int)sizeof(result) * 8) {
return 0; // underflow
}
if (exponent > 0) {
result <<= exponent; // possible overflow
} else {
result >>= -exponent;
}
if (sign) result = -result; // handle sign
return result;
}