What is the best way to round double to two decimal places?
For example, I want to convert
3.45345323423423E+28
to
3.45
What is the best way to round double to two decimal places?
For example, I want to convert
3.45345323423423E+28
to
3.45
You are aware that 3.45345323423423E+28
is a pretty large number and does not contain a decimal part?
(Stripping the scientific notation, your number is 34,534,532,342,342,300,000,000,000,000 which is, of course, an integer).
If you want to round a number to 2 decimal places then use Math.Round(value, 2);
But do be aware that your example number will not be changed.
If however, you want to round to 2 significant figures, then see this answer: Round a double to x significant figures
Use this:
Math.Round(value, 2);
This will round up your value to 2 decimal places.
Store it in some variable or display it.
First of all you should consider using some other data type for such large number. Perhaps decimal. Because precision of double is only up to 15-16 digits.
If you still persist with double then you can use Math.Round here.
double db = 3.45345323423423E+28;
db = Math.Round(db, 2);
However, if you change your mind to switch to decimal then following should do the trick.
decimal d = 3.45345323423423E+28m;
d = decimal.Round(d, 2);
I think you want to display it like this: 3.45E+28
Then you should do something like this:
double number = 3.45345323423423E+28;
string result = number.ToString("0.00E+00");
Hope this will help you in your quest.