Scala 中的数字格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1350566/
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
Number formatting in Scala?
提问by Daniel C. Sobral
I have a dynamically changing input reading from a file. The numbers are either Intor Double. Why does Scala print .0after every Doublenumber? Is there a way for Scala to print it the same way it reads it?
我从文件中读取了动态变化的输入。数字是Int或Double。为什么 Scala 会.0在每个Double数字之后打印?Scala 有没有办法像读取它一样打印它?
Example:
例子:
var x:Double = 1
println (x) // This prints '1.0', I want it to print '1'
x = 1.0 // This prints '1.0', which is good
I can't use Intbecause some of the input I get are Doubles. I can't use Stringor AnyValbecause I perform some math operations.
我无法使用,Int因为我得到的一些输入是Doubles。我不能使用String或AnyVal因为我执行了一些数学运算。
Thank you,
谢谢,
回答by Daniel C. Sobral
scala> "%1.0f" format 1.0
res3: String = 1
If your input is either Intor Double, you can do it like this:
如果您的输入是Int或Double,您可以这样做:
def fmt(v: Any): String = v match {
case d : Double => "%1.0f" format d
case i : Int => i.toString
case _ => throw new IllegalArgumentException
}
Usage:
用法:
scala> fmt(1.0)
res6: String = 1
scala> fmt(1)
res7: String = 1
scala> fmt(1.0f)
java.lang.IllegalArgumentException
at .fmt(<console>:7)
at .<init>(<console>:6)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:4)
at RequestResult$.<clinit>(<console>)
at RequestResult$result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.Dele...
Otherwise, you might use BigDecimals. They are slow, but they do come with the scale, so "1", "1.0" and "1.00" are all different:
否则,您可能会使用BigDecimals. 它们很慢,但它们确实有比例尺,所以“1”、“1.0”和“1.00”都是不同的:
scala> var x = BigDecimal("1.0")
x: BigDecimal = 1.0
scala> x = 1
x: BigDecimal = 1
scala> x = 1.0
x: BigDecimal = 1.0
scala> x = 1.000
x: BigDecimal = 1.0
scala> x = "1.000"
x: BigDecimal = 1.000
回答by nuriaion
var x:Double = 1
var y:Double = 1.0
print(x) // => 1.0
print(y) // => 1.0
If i understand you question you want scala to print x and y differently? The problem is that x and y are both a variable of the type Double and look the same.
如果我理解您的问题,您希望 Scala 以不同的方式打印 x 和 y?问题是 x 和 y 都是 Double 类型的变量并且看起来相同。
Why do you explicitly define the type of the vars?
为什么要明确定义 vars 的类型?
var x = 1
var y= 1.0
print(x) // => 1
print(y) // => 1.0
回答by Jesper
Use printf:
使用printf:
printf("The value is %.0f", x)
For a description of the format string, see this pagefrom the Java SE 6 API documentation.
有关格式字符串的说明,请参阅Java SE 6 API 文档中的此页面。
Note that you can ofcourse also use the Java library from Scala, so other ways to format numbers from Java can also be used from Scala. You can for example use class java.text.DecimalFormat:
请注意,您当然也可以使用 Scala 的 Java 库,因此也可以从 Scala 使用其他格式化 Java 数字的方法。例如,您可以使用 class java.text.DecimalFormat:
val df = new java.text.DecimalFormat("#####")
println(df.format(x))
回答by juancn
The use of a "_.0" at the end of floating point numbers is a convention. Just a way to know that the number is actually floating point and not an integer.
在浮点数末尾使用“_.0”是一种约定。只是一种知道数字实际上是浮点数而不是整数的方法。
If you reallyneed to "to print it the same way it reads it" you may have to rethink the way your code is structured, possibly preserving your input data. If it's just a formatting issue, the easiest way is to convert the values to integers before printing:
如果您真的需要“以与读取相同的方式打印它”,您可能必须重新考虑代码的结构方式,可能会保留您的输入数据。如果只是格式问题,最简单的方法是在打印前将值转换为整数:
val x = 1.0
println(x.toInt)
If some are integers and some are not, you need a bit more code:
如果有些是整数而有些不是,则需要更多代码:
def fmt[T <% math.ScalaNumericConversions](n : T) =
if(n.toInt == n) n.toInt.toString else n.toString
val a : Double = 1.0
val b : Double = 1.5
val c : Int = 1
println(fmt(a))
println(fmt(b))
println(fmt(c))
The code above should print:
上面的代码应该打印:
1
1.5
1
The signature of the fmtmethod accepts any type that either is a subtype of ScalaNumericConversionsor can be converted to one through implicit conversions (so we can use the toIntmethod).
该fmt方法的签名接受任何类型,这些类型要么是其子类型,要么ScalaNumericConversions可以通过隐式转换转换为一个子类型(因此我们可以使用该toInt方法)。
回答by cdmckay
Starting with Scala 2.10 you can use the finterpolator:
使用Scala 2.10开始,你可以使用的f插:
scala> val x: Double = 1
x: Double = 1.0
scala> println(f"$x%.0f")
1
scala> val i = 1
i: Int = 1
scala> println(f"$i%.0f")
1
回答by Xavier Guihot
If you are working with a Doubleand want to format it as a Stringwithout .0when it's a whole number and with its decimals otherwise, then you could use String::stripSuffix:
如果您正在使用 aDouble并希望将其格式化为 a ,String而.0不是整数,否则为小数,那么您可以使用String::stripSuffix:
x.toString.stripSuffix(".0")
// val x: Double = 1.34 => "1.34"
// val x: Double = 1.0 => "1"
回答by Synesso
Use type inference, rather than explicit typing.
使用类型推断,而不是显式类型。
scala> val xi = 1
xi: Int = 1
scala> val xd = 1.0
xd: Double = 1.0
scala> println(xi)
1
scala> println(xd)
1.0

