Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ convert a fractional part of a number into integer

Tags:

c++

integer

math

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,

like image 887
user1731805 Avatar asked Oct 09 '12 13:10

user1731805


2 Answers

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));
}
like image 83
digitalvision Avatar answered Sep 28 '22 03:09

digitalvision


#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
}
like image 24
moooeeeep Avatar answered Sep 28 '22 05:09

moooeeeep