scala 中的字符串格式 - 最大十进制精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8203238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:41:15  来源:igfitidea点击:

String formatting in scala - maximum decimal precision

scala

提问by Ben Dilts

"%.3f".format(1)returns 1.000.
"%.3f".format(4.0/3.0)returns 1.333.

"%.3f".format(1)返回1.000
"%.3f".format(4.0/3.0)返回1.333

Is there some easy way to have these return 1and 1.333? I thought the standard printfformat specified that precision as the maximum already, but apparently not in Scala.

有一些简单的方法来拥有这些回报11.333?我认为标准printf格式已经将精度指定为最大值,但显然不在 Scala 中。

回答by huynhjl

The default formatter used by printf seems to be a generic one that doesn't have all the same support than [DecimalFormat][1]. You can instantiate a custom formatter along those lines:

printf 使用的默认格式化程序似乎是一种通用格式化程序,与[DecimalFormat][1]. 您可以按照以下方式实例化自定义格式化程序:

scala> import java.text.DecimalFormat 
import java.text.DecimalFormat

scala> val formatter = new DecimalFormat("#.###")
formatter: java.text.DecimalFormat = java.text.DecimalFormat@674dc

scala> formatter.format(1)
res36: java.lang.String = 1

scala> formatter.format(1.34)
res37: java.lang.String = 1.34

scala> formatter.format(4.toFloat / 3)
res38: java.lang.String = 1.333

scala> formatter.format(1.toFloat)
res39: java.lang.String = 1

See: http://docs.oracle.com/javase/tutorial/java/data/numberformat.htmlfor more information.

有关更多信息,请参见:http: //docs.oracle.com/javase/tutorial/java/data/numberformat.html

回答by David

"%.3f".format(1)will throw an java.util.IllegalFormatConversionExceptionbecause of the wrong type (Floatis expected and you give a Int).

"%.3f".format(1)会抛出一个java.util.IllegalFormatConversionException因为错误的类型(Float是预期的,你给出了一个Int)。

Even if you use "%.3f".format(1.0), you will get 1.000.

即使你使用"%.3f".format(1.0),你也会得到1.000

You can use a method like the following to obtain the expected result :

您可以使用类似以下的方法来获得预期的结果:

def format(x:AnyVal):String = x match {
  case x:Int => "%d".format(x)
  case x:Long => "%d".format(x)
  case x:Float => "%.3f".format(x)
  case x:Double => "%.3f".format(x)
  case _ => ""
}

This method will return the expected format based on argument type.

此方法将根据参数类型返回预期格式。

回答by themel

How about simply getting rid of the zeroes after formatting?

格式化后简单地去掉零怎么样?

scala> Array(1.0,1.10,1.110).map("%.3g" format _).map(_.replaceAll("[.0]*$",""))
res7: Array[java.lang.String] = Array(1, 1.1, 1.11)