How to Convert First Digit after Decimal to Integer?

I am writing a program that involves some periodic motion and, instead of tracking the specific period and time interval within that period, I am planning to instead use the interval as a fraction of the overall period. So, the time variable will always be a real number (type double) in the range 0 - 1.

I'd also like to use the first digit after the decimal as an array index. ( The array will contain pre-assigned data to speed up program execution.) For example, if the variable is 0.314159, I would like to use the '3', convert it to an integer, and use it to access the array.

At this point, I am thinking the procedure will go somewhat like the following:

1
2
3
4
5
double time_interval; // Say 0.314159
int arr_index; // Array index

arr_index = floor(10.0 * time_interval); // Can now use arr_index to access array.


Is this okay?
Should the last line explicitly cast the result as an int?

Is there a better way to do this? Any suggestions welcome.
What is the best way to grab the first digit after the decimal, convert it to an integer, and use it as an integer throughout the rest of the program?

Last edited on
if the variable is 0.314159, I would like to use the '3', convert it to an integer, and use it to access the array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# include <sstream>
# include <iostream>
# include <string>

int main()
{
    double time_interval = 0.314159;

    std::stringstream stream {};

    stream << time_interval;

    std::string integral{}, decimal{};

    getline(stream, integral, '.') && getline(stream, decimal);
    //short-circuit evaluation
    //also recommend usual validation that there is an actual decimal present etc

    std::istringstream firstNum{std::string{decimal[0]}};
    //peel off the first digit of the fractional part

    int arr_index{};

    firstNum >> arr_index;

    std::cout << arr_index << "\n";
}

Is this okay?
Should the last line explicitly cast the result as an int?

Looks good.
Though, you don't need to call floor(). Explicitly casting 10.0 * time_interval as an int will do the same thing.
 
arr_index = static_cast<int>( 10.0 * time_interval );
Thanks for the replies.

This is some good information. Now to put it into action and update the program.
Topic archived. No new replies allowed.