1

Sorry for the daft question, but I get back this value from database

"7.545720553985866E+29"

I need to convert this value to a decimal, rounded to 6 digits. What is the best way to do that? I tried

var test = double.Parse("7.545720553985866E+29");
test = Math.Round(test, 6);
var test2 = Convert.ToDecimal(test);

but the value remains unchanged and the conversion crashes.

AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
  • 1
    `Math.Round(test, 6)` rounds to 6 decimal places _after_ decimal point. But your number is large enough, it's actually something like `754572055398586600000000000000.0`, so it's already rounded. – Vlad Feb 11 '19 at 16:16

3 Answers3

3

Math.Round rounds to N digits to the right of the decimal point. Your number has NO digits to the right of the decimal (it is equivalent to 754,572,055,398,586,600,000,000,000,000), so rounding it does not change the value.

If you want to round to N significant digits then look at some of the existing answers:

Round a double to x significant figures

Rounding the SIGNIFICANT digits in a double, not to decimal places

the conversion crashes.

That's because the value is too large for a decimal. The largest value a decimal can hold is 7.9228E+28 - your value is about 10 times larger than that.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

Maybe you can substring it and then after, parse.

var test= "7.545720553985866E+29".Substring(0,8); // 7.545720

test = Math.Round(test, 6);

var test2 = Convert.ToDecimal(test);

Mr.Deer
  • 476
  • 6
  • 17
0

You can use this to round to 6 significant digits:

round(test, 6 - int(math.log10(test)))

The resulting value from that is

7.545721e+29

This works by using log10 from the math module to get the power of 10 in test, rounds it down to get an integer, subtracts that from 6 then uses round to get the desired digits.

As noted by others, round works to the given number of decimal places. The log10 and the rest figures how many decimal places are needed to get the desired number of significant digits. If the decimal places are negative, round rounds to the left of the decimal point.

You should be aware that log10 is not perfectly accurate and taking the int of that may be off from the expected value by one. This happens rarely but it does happen. Also, even if the computed value is correct, converting the value to string (such as when you print it) may give a different-than-expected result. If you need perfect accuracy you would be better off working from the string representation of the value.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50