字符串格式与最大数字位数(String formatting with maximum number of digits)

系统教程 行业动态 更新时间:2024-06-14 17:02:18
字符串格式与最大数字位数(String formatting with maximum number of digits)

我试图用最大位数格式化浮点数,但我不想要不必要的尾随零 。 我想如果我用g代替f它会起作用(参考这个问题 )

def testF(d: Double) = f"$d%1.2f" def testG(d: Double) = f"$d%1.2g"

现在这表现得很奇怪:

testF(3.1415) // --> 3.14 ok testF(3.1) // --> 3.10 hmmm, don't want that zero testG(3.1415) // --> 3.1 what the ?

好吧,或许我需要为g增加一位:

def testG(d: Double) = f"$d%1.3g" testG(3.1415) // --> 3.14 ok testG(3.1) // --> 3.10 grmpf

所以有两个问题 - 一个,为什么gck会丢掉一位数字,而且似乎不关心尾随零? 二,我怎么能

testX(3.1415) // --> 3.14 testX(3.1) // --> 3.1

I'm trying to format floating point numbers with a maximum number of digits, but I don't want unnecessary trailing zeroes. I thought if I use g instead of f it would work (cf. this question)

def testF(d: Double) = f"$d%1.2f" def testG(d: Double) = f"$d%1.2g"

Now this behaves rather strangely:

testF(3.1415) // --> 3.14 ok testF(3.1) // --> 3.10 hmmm, don't want that zero testG(3.1415) // --> 3.1 what the ?

Ok, so perhaps I need to increase the digits by one for g:

def testG(d: Double) = f"$d%1.3g" testG(3.1415) // --> 3.14 ok testG(3.1) // --> 3.10 grmpf

So two questions—one, why the heck is g dropping one digit and doesn't seem to care about trailing zeroes? Two, how can I have

testX(3.1415) // --> 3.14 testX(3.1) // --> 3.1

?

最满意答案

您可以使用java DecimalFormat,但它可能不会取悦眼睛:

def testX(d: Double) = new java.text.DecimalFormat("#.##").format(d)

同样为了回答你的第一个问题, 为什么heck会丢掉一个数字,而且似乎不关心尾随零

对于浮点转换“e”,“E”和“f”,精度是小数点分隔符后的位数 。 如果转换为'g'或'G',则精度是四舍五入后得到的幅度中的总位数

格式化程序细节

You could use the java DecimalFormat but it may not please the eye:

def testX(d: Double) = new java.text.DecimalFormat("#.##").format(d)

Also to answer your first question why the heck is g dropping one digit and doesn't seem to care about trailing zeroes

For the floating-point conversions 'e', 'E', and 'f' the precision is the number of digits after the decimal separator. If the conversion is 'g' or 'G', then the precision is the total number of digits in the resulting magnitude after rounding.

Formatter details

更多推荐

本文发布于:2023-04-21 18:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/cd6fe88362bfe3a429b7135cb720406c.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位数   字符串   格式   数字   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!