简体   繁体   中英

Converting Exponential Double value to int in C#

I want to get the only that part which is before the point but I am unable to get it with every method. My value is 1.734565456765434E-06. I want to convert it into just 1

Looks like you're trying to get the most significant digit of a number .

var n = 1.734565456765434E-06;
var exp = Math.Floor(Math.Log10(n)); // -6
var result = Math.Floor(n / Math.Pow(10, exp)); // 1

This can be generalized to this:

var n = 1.734565456765434E-06;
var nDigits = 1; // 1 significant digit
var exp = Math.Floor(Math.Log10(n));
var result = Math.Floor(n / Math.Pow(10, exp + (1 - nDigits)));

If you are only interested in the first digit of your scientific representation, try this:

var number = 1.734565456765434E-06;
var numberString = number.ToString("E");
var firstDigitString = numberString.Substring(0, 1);
var firstDigit = int.Parse(firstDigitString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM