是否有任何标准库可将float64转换为具有最大有效位数的固定宽度的字符串? [英] Is there any standard library to convert float64 to string with fix width with maximum number of significant digits?

查看:197
本文介绍了是否有任何标准库可将float64转换为具有最大有效位数的固定宽度的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设要在12个固定宽度的表格中进行打印,我们需要打印float64个数字:

Imagine for printing in a 12 fixed width table we need printing float64 numbers:

fmt.Printf("%12.6g\n", 9.405090880450127e+119) //"9.40509e+119"
fmt.Printf("%12.6g\n", 0.1234567890123)        //"    0.123457"
fmt.Printf("%12.6g\n", 123456789012.0)         //" 1.23457e+11"

我们首选0.1234567890而不是"0.123457",我们输掉6个有效数字.
我们宁愿将123456789012替换为"1.23457e + 11",也要输掉6个有效数字.

We prefer 0.1234567890 to " 0.123457" we lose 6 significant digits.
We prefer 123456789012 to " 1.23457e+11" we lose 6 significant digits.

是否有标准库可以将固定宽度的float64转换为string,且有效位数最大? 预先感谢.

Is there any standard library to convert float64 to string with fix width with maximum number of significant digits? Thanks in Advance.

推荐答案

基本上,您有2种输出格式:科学计数法或常规格式.这两种格式之间的转折点是1e12.

Basically you have 2 output formats: either a scientific notation or a regular form. The turning point between those 2 formats is 1e12.

因此,如果x >= 1e12,则可以分支.在两个分支中,您都可以使用0个小数位数进行格式化,以查看数字的长度,因此您可以计算12个宽度中可以容纳多少个小数位数,从而可以使用计算出的精度构造最终的格式字符串

So you can branch if x >= 1e12. In both branches you may do a formatting with 0 fraction digits to see how long the number will be, so you can calculate how many fraction digits will fit in for 12 width, and so you can construct the final format string, using the calculated precision.

科学表示法(%g)也需要进行预检查,因为指数的宽度可能会有所不同(例如e+1e+10e+100).

The pre-check is required in the scientific notation too (%g), because the width of exponent may vary (e.g. e+1, e+10, e+100).

这是一个示例实现.这是入门,但这并不意味着要处理所有情况,它也不是最有效的解决方案(但相对简单,可以完成工作):

Here is an example implementation. This is to get you started, but it does not mean to handle all cases, and it is not the most efficient solution (but relatively simple and does the job):

// format12 formats x to be 12 chars long.
func format12(x float64) string {
    if x >= 1e12 {
        // Check to see how many fraction digits fit in:
        s := fmt.Sprintf("%.g", x)
        format := fmt.Sprintf("%%12.%dg", 12-len(s))
        return fmt.Sprintf(format, x)
    }

    // Check to see how many fraction digits fit in:
    s := fmt.Sprintf("%.0f", x)
    if len(s) == 12 {
        return s
    }
    format := fmt.Sprintf("%%%d.%df", len(s), 12-len(s)-1)
    return fmt.Sprintf(format, x)
}

测试:

fs := []float64{0, 1234.567890123, 0.1234567890123, 123456789012.0, 1234567890123.0,
    9.405090880450127e+9, 9.405090880450127e+19, 9.405090880450127e+119}

for _, f := range fs {
    fmt.Println(format12(f))
}

输出(在转到游乐场上尝试):

0.0000000000
0.1234567890
1234.5678901
123456789012
1.234568e+12
9405090880.5
9.405091e+19
9.40509e+119

这篇关于是否有任何标准库可将float64转换为具有最大有效位数的固定宽度的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆