#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <stdexcept>
/**
* Returns the Nth digit after the decimal point.
*
* Examples:
* getNthDecimalDigit(123.456789, 1) -> 4
* getNthDecimalDigit(123.456789, 2) -> 5
* getNthDecimalDigit(123.456789, 3) -> 6
*
* @param value Floating-point number.
* @param position Digit position after the decimal point (1-based).
* @return The requested digit, or 0 if it does not exist.
*
* @throws std::invalid_argument if position < 1.
*/
int getNthDecimalDigit(double value, int position)
{
if (position < 1)
{
throw std::invalid_argument(
"Position must be greater than 0.");
}
// Convert the absolute value to a string with high precision
std::ostringstream oss;
oss << std::fixed
<< std::setprecision(15)
<< std::abs(value);
std::string str = oss.str();
// Find the decimal point
std::size_t decimalPos = str.find('.');
if (decimalPos == std::string::npos)
{
return 0;
}
// Locate the requested digit
std::size_t digitIndex = decimalPos + position;
if (digitIndex >= str.length())
{
return 0;
}
return str[digitIndex] - '0';
}
int main()
{
const double number = 123.456789123456789;
std::cout << std::fixed
<< std::setprecision(16)
<< number
<< '\n';
// Print the first 15 digits after the decimal point
for (int i = 1; i <= 15; ++i)
{
std::cout
<< i
<< " digit after decimal = "
<< getNthDecimalDigit(number, i)
<< '\n';
}
std::cout << "\nAdditional Examples\n";
std::cout << "-------------------\n";
std::cout
<< "123.456789, position 4 -> "
<< getNthDecimalDigit(123.456789, 4)
<< '\n';
std::cout
<< "-98.7654, position 2 -> "
<< getNthDecimalDigit(-98.7654, 2)
<< '\n';
std::cout
<< "1.2, position 5 -> "
<< getNthDecimalDigit(1.2, 5)
<< '\n';
return 0;
}
// 123.456789123456789 original number
// 123.456789123456787
/*
run:
123.4567891234567867
1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9
7 digit after decimal = 1
8 digit after decimal = 2
9 digit after decimal = 3
10 digit after decimal = 4
11 digit after decimal = 5
12 digit after decimal = 6
13 digit after decimal = 7
14 digit after decimal = 8
15 digit after decimal = 7
Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0
*/