开发者

How to format the exponent of a floating point number in printf %E (scientific)

开发者 https://www.devze.com 2023-03-22 06:28 出处:网络
When I use 开发者_Go百科sprintf(\'%E\',@value) for some large arbitrary value, e.g. 3.14158995322368e+22f

When I use

开发者_Go百科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).


Ruby's sprintf is just a wrapper around the native libc snprintf. From sprintf.c (Ruby 1.9.2-p180):

/*   
 *  call-seq:
 *     format(format_string [, arguments...] )   -> string
 *     sprintf(format_string [, arguments...] )  -> string 
 * [...]
 */

VALUE
rb_f_sprintf(int argc, const VALUE *argv)
{
    return rb_str_format(argc - 1, argv + 1, GETNTHARG(0));
}

And inside rb_str_format, we find this:

case 'f':
case 'g':
case 'G':
case 'e':
case 'E':
case 'a':
case 'A':
    /* ... */
    snprintf(&buf[blen], need, fbuf, fval);

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 sprintf doesn'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 sprintf and then normalize the format with some greasy regex mangling. Not exactly a pleasant solution but you do what you have to do.

0

精彩评论

暂无评论...
验证码 换一张
取 消