作者:WenWu_Both
出处:http://blog.csdn.net/wenwu_both/article/
版权:本文版权归作者和CSDN博客共有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文链接;否则必究法律责任
Scala所有的数值都是对象,包括Bytes、char、Double、Float、 Int、Long和Short。
1.从字符串到数值
使用String的to*方法:
"100".toInt
"100".toDouble
"100".toByte
BigInt和BigDecimal也可以通过字符串创建:
val a = BigInt("1")
val b = BigDecimal("3.1415926")
处理基数和根,Scala中的toInt方法不支持传入进制,为解决这个问题,可以使用 java.lang.Integer类的parseInt方法:
Integer.parseInt("100",2)
Integer.parseInt("100",8)
Integer.parseInt("100",16)
也可以通过隐式转换类的方法来解决这个问题:
implicit class StringToInt(s: String){
def toInt(radix: Int) = Integer.parseInt(s, radix)
}
"100".toInt(2)
处理NumberFormatException时,通常使用Option/Some/None模式来处理这类问题:
def toInt(s: String): Option[Int] = {
try{
Some(s.toInt)
}catch{
case e: NumberFormatException => None
}
}
通过getOrElse方法调用:
println(toInt("1").getOrElse(0)) // 1
println(toInt("a").getOrElse(0)) // 0
或者通过模式匹配调用:
toInt("a") match{
case Some(n) => println(n)
case None => println("Boom!That wasn't a number!")
}
// 返回值
var result = toInt("a") match{
case Some(n) => n
case None => 0)
}
2.数值类型转换
to*方法
3.替代++和–
Scala中无++、–操作符,可用+=和-=替代。
4.浮点数的比较
val a = 0.3 // 0.3
val b = 0.1 + 0.2 // 0.30000000000000004
a == b // False
解决方法:自定义约等于方法
object MathUtils{
def ~=(x:Double, y:Double, precision:Double){
if((x-y).abs < peecision) true else false
}
}
// 静态方法调用
MathUtils.~=(a, b, 0.000001)
5.生成随机数
使用Scala的Scala.util.random:
val r = scala.util.random
r.nextInt
r.nextInt(100)
r.nextDouble
6.生成区间数
val a = 1 to 100 // [1, 100]
val a = 1 until 100 // [1, 100)
val a = 1 to 100 by 3 // 3为步长