2013-10-25 101 views
0

我需要檢查一個數字中的位數是否等於某個其他數字。我能想到的最佳方式是:檢查斯卡拉的數字位數

require(Number.toString == """\d{8}""", throw new InvalidDateFormatException("Wrong format for string parameter")) 

其中需要的位數是8.有沒有更好的方法?

+0

'字符串== regex'可能永遠不會評估爲true,因爲'=='不計算正則表達式。改用'matches'。 – sschaef

回答

5

一種選擇:

require(Number.toString.length == 8, throw new InvalidDateFormatException("Wrong format for string parameter")) 
0

另一種方法是

require(Number > 9999999 && Number < 100000000,throw new InvalidDateFormatException("Wrong format for string parameter")) 
0

不是非常優雅,但要避免轉化爲字符串:

def check(num: Int, digits: Int) = { 
    val div = math.pow(10, digits - 1) 

    num < div * 10 && num > div - 1 
} 

println(check(12345678, 8)) // true 
println(check(12345678, 9)) // false 
println(check(12345678, 7)) // false 
1

另一個(學術)的方法是計數數字:

def digits(num: Int) = { 
    @scala.annotation.tailrec 
    def run(num: Int, digits: Int): Int = 
    if(num > 0) run(num/10, digits + 1) 
    else  digits 

    run(math.abs(num), 0) 
} 

例如,您可以使用隱式轉換將digits方法添加到現有的數字類型中。

我很樂意承認這是過度殺傷性的,並且可能是過早的優化。

0

像這樣的東西應該得到您小數

def countDecimals(d: Double): Int = (BigDecimal(d) - BigDecimal(d.toInt)).precision 

countDecimals(10321.1234) == 4 // True 

和數量,如果你想獲得數全長:

BigDecimal(d).precision 

BigDecimal(10321.1234).precision == 9 // True 
+0

不完全確定這個'.precision'是如何工作的。 'BigDecimal(0.00034).precision'返回:'Int 2' – user7552