Get the last (i.e. Endswith) 3 decimal digit (.NET)

I can use Math for evil ... But in a number written as 0.7000123 I need to get "123". That is, I need to extract the last 3 digits in the decimal part of the number. The least significant numbers when the first few are what most people need.

Examples:

0.7500123 -> 123  
0.5150111 -> 111

It always starts with the number 5. And yes, I keep secret information inside this number, in part of the decimal, which will not affect how the number is used - this is a potentially evil part. But this is still the best way to solve a specific problem.

I am wondering if mathematical or string manipulation is the least dodgy way to do this.

Performance is not a problem because I call it once.

Can anyone see a simple math way to do this? For example, a combination of mathematical functions (I missed) in .NET?

+5
source share
4 answers

This is a strange request to be sure. But one way to get the int value from the last three digits is as follows:

int x = (int)((yourNumber * 10000000) % 1000);

I'm going to guess that there is a better way to get the information you are looking for cleaner, but given what you requested, this should work.

+5
source

Convert your number to string first.

string s = num.ToString();


string s1 =  s.Substring(s.Length - 3, 3);

Now s1 contains the last 3 digits of the number

+3
source

Using modulo, you get the last 3 digits:

var d = 0.7000123m;
d = d * 10000000 % 1000;

d will now have a value of 123.

+2
source

Try the following:

    string value= "0.1234567";
    string lastthreedigit= value.Substring(value.Length - 3);
0
source

All Articles