I have a code for which I get a long exponential number eg. a = 2.572920056e-3 as the output. I need to round off only the non-exponential part i.e I want the output to be something like 2.573e-3.
I know how to round off integers using ceil, round etc, but how can one round off only the number outside the exponential like mentioned above. Also, the output varies so I cannot use a command with a fixed number like
(ceil(a*10^6)/10^6).
(The fixed number being '6' in this case).

 채택된 답변

Walter Roberson
Walter Roberson 2013년 1월 17일
편집: Walter Roberson 2013년 1월 17일

1 개 추천

ex = 10^(3-floor(log10(a)));
ar = round(a * ex) / ex;
Caution: might not work for 0 or infinities

댓글 수: 6

Nitin Samuel
Nitin Samuel 2013년 1월 17일
Thank you so much Mr.Roberson..works fine !.just one more thing..I actually want it to be in the form x.xx*e(x)...Whereas now its in the form x.xxxx*e(x)...its a GUI and the user will not want to see too many figures in an edit box... Can something be done about that? Thanks a lot again...
Nitin Samuel
Nitin Samuel 2013년 1월 17일
편집: Nitin Samuel 2013년 1월 17일
even if 3 is changed to 2 in your code, it adds a 0 making it in the form x.xxxx again..
Walter Roberson
Walter Roberson 2013년 1월 17일
편집: Walter Roberson 2013년 1월 17일
How are you doing the formatting for the edit box?
Note: if all of this is just for display purposes, there is no need to do the computation I showed here.
sprintf('%.2e', a)
Nitin Samuel
Nitin Samuel 2013년 1월 17일
This works fine! This code I shall use for display purposes and the one you gave earlier shall be used for report generation for extra accuracy.Thanks a lot Mr. Roberson..!
Mikhail Lisakov
Mikhail Lisakov 2015년 11월 16일
편집: Walter Roberson 2015년 11월 16일
Solution is great but fails for powers > 0 (though I've used it to round significand to integer).
To account for possible powers greater than 0 there should be a condition like this :
if(ex < 0)
ar = round(a * ex) / ex;
} else {
ar = round(a / ex) * ex;
}
Walter Roberson
Walter Roberson 2015년 11월 16일
Different requirement, Mikhail. That formula would be for rounding decimals after the decimal point in fixed point format, but the original question was for rounding in engineering format.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

질문:

2013년 1월 17일

댓글:

2015년 11월 16일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by