Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to find the digit at n position in a decimal number?

Background

I'm working on a symmetric rounding class and I find that I'm stuck with regards to how to best find the number at position x that I will be rounding. I'm sure there is an efficient mathematical way to find the single digit and return it without having to resort to string parsing.

Problem

Suppose, I have the following (C#) psuedo-code:

var position = 3;
var value = 102.43587m;
// I want this no ↑ (that is 5)

protected static int FindNDigit(decimal value, int position)
{
    // This snippet is what I am searching for
}

Also, it is worth noting that if my value is a whole number, I will need to return a zero for the result of FindNDigit.

Does anyone have any hints on how I should approach this problem? Is this something that is blaringly obvious that I'm missing?

like image 804
Elijah Avatar asked May 27 '10 17:05

Elijah


People also ask

How do you find the digits of a decimal?

The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left. The number.

What position of a decimal is one number to the right of the decimal point?

One decimal place to the left of the decimal point is the ones place. One decimal place to the right of the decimal place is the tenths place.

How do you find the value of a digit in a number?

We calculate it by multiplying the place value and face value of the digit. For instance: If we consider the number 45. Here digit 4 is in the tens column. Hence, the value of the digit 4 will be i.e. 40 or forty.


1 Answers

(int)(value * Math.Pow(10, position)) % 10
like image 123
Andrey Avatar answered Oct 25 '22 11:10

Andrey