sprintf('%d',x) prints out exponential notation instead of decimal notation

357 views (last 30 days)
I am using version ' (R2014a)'. The sprintf command seems to print out exponential notation when decimal notation is requested (second and third example):
ans = 105
ans = 1.100000e+02
ans = 1e+02
Is there any reason why the last two calls are not printing '110'?
summyia qamar
summyia qamar on 16 Dec 2016
what if we want to change 10.3?what will be the format?%g is not working.

Sign in to comment.

Accepted Answer

per isakson
per isakson on 26 Aug 2014
Edited: per isakson on 26 Aug 2014
What you see is a consequence of how floating point arithmetic works.
1.05*100 evaluates to a whole number (flint). The other two don't.
per isakson
per isakson on 26 Aug 2014
Somewhere down the page fprintf, Write data to text file it says:
If you specify a conversion that does not fit the data, such as
a string conversion for a numeric value, MATLAB overrides the
specified conversion, and uses %e.
To me this was "expected behavior", but I had to look it up now. One cannot read and remember everything. Thus, when in doubt make a test
>> sprintf( '%d', 1/3 )
ans =

Sign in to comment.

More Answers (2)

Andrew Reibold
Andrew Reibold on 26 Aug 2014
Edited: Andrew Reibold on 26 Aug 2014
Use f instead of d for floating point notation will stop the scientific I believe.
ans = 105.000000
ans = 110.000000
ans = 110
Notice I can stop the decimals by using .0f like I did in the last example.
For additional reference:
James Tursa
James Tursa on 17 Dec 2016
This is what is happening "under the hood" with the floating point numbers (neither 1.05 nor 1.10 can be represented exactly in IEEE double):
>> num2strexact(1.05)
ans =
>> num2strexact(1.05*100)
ans =
>> num2strexact(1.10)
ans =
>> num2strexact(1.10*100)
ans =
You got lucky on the 1.05*100 that it resulted in 105 exactly, but you didn't get lucky in the 1.10*100 case.

Sign in to comment.

Sebastian Mader
Sebastian Mader on 27 Jul 2018
So why did Mathworks introduce %d and %i at all? It would be safer to use %.0f in any case.
Sebastian Mader
Sebastian Mader on 27 Jul 2018
I see your Point, thanks for being very clary on this, much appreciated. I am far from the Limits, where rounding becomes an issue with '%.0f', so I can savely use this approach.
Nonetheless, I believe that the comments on "Notable Behavior of Conversions with Formatting Operators" should be moved up in the documentation and the special case of using %d with double precison numbers mentioned. It is at least to me not obvious at all, that an implicit type conversion is not performed by fprintf despite my desire to print an integer.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by