Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last (ie endswith) 3 digits of a decimal (.NET)

Tags:

c#

.net

I may be using Math for evil... But, in a number written as 0.7000123 I need to get the "123" - That is, I need to extract the last 3 digits in the decimal portion of a number. The least significant digits, when the first few are what most people require.

Examples:

0.7500123 -> 123  
0.5150111 -> 111

It always starts from digit 5. And yes, I'm storing secret information inside this number, in the part of the decimal that will not affect how the number is used - which is the potentially evil part. But it's still the best way around a certain problem I have.

I'm wondering whether math or string manipulation is the least dodgy way of doing this.

Performance is not an issue, at all, since I'm calling it once.

Can anyone see an easy mathematical way of doing this? eg A combination of Math functions (I've missed) in .NET?

like image 515
PandaWood Avatar asked Apr 22 '13 03:04

PandaWood


People also ask

How do you find last n digits?

To find last digit of a number, we use modulo operator %. When modulo divided by 10 returns its last digit. To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10.

How do you get precision in C#?

var result = Math. Pow(0.1, precision); There is another thing you could try - the Decimal type stores an internal precision value. Therefore you could use Decimal.

Is numeric check in C#?

IsNumeric() function in C# IsNumeric() function returns True if the data type of Expression is Boolean, Byte, Decimal, etc or an Object that contains one of those numeric types, It returns a value indicating whether an expression can be converted to a numeric data type.


2 Answers

It's a strange request to be sure. But one way to get an int value of the last 3 digits is like so:

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

I'm going to guess there's a better way to get the information you're looking for that's cleaner, but given what you've asked for, this should work.

like image 100
Gjeltema Avatar answered Sep 20 '22 00:09

Gjeltema


First Convert Your number into the String.

string s = num.ToString();


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

Now s1 Contains Last 3 Digits Of the Number

like image 29
Rahul Jhala Avatar answered Sep 20 '22 00:09

Rahul Jhala