When I use
sprintf('%E',@value)
for some large arbitrary value,
e.g. 3.14158995322368e+22f
it prints
3.14158995322368e+ 0 22
How can I format the exponent? E.g. no leading 0 (2 digits) or always 3 or 4 digits (1 or 2 leading zeroes).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Ruby’s
sprintfis just a wrapper around the native libcsnprintf. Fromsprintf.c(Ruby 1.9.2-p180):And inside
rb_str_format, we find this:So you should get the same results on a single platform but not necessarily the same results on different platforms (even after taking the usual floating point issues into account). Ruby’s
sprintfdoesn’t offer any way to control the specific formatting of the exponent so you are at the mercy of the OS’s libc (i.e. you of luck, libc has no mercy).If necessary, you could use
sprintfand then normalize the format with some greasy regex mangling. Not exactly a pleasant solution but you do what you have to do.