小品:number_to_human 的中英文竟然不同調!

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
557   0  
·
2020/09/03
·
2 mins read


有人說 Rails 超好用,但也有人說 Rails 要用到精,很難,都對,因為,Rails 的挫折,總是就發生在轉角處。

我很久很久以前,用了 Rails 內建的一個 helper,目的很單純,就是把數字轉成對人類閱讀友善的格式,也就是,例如將:123456 轉成 123K,在 Rails 中,就是:

number_to_human (ActionView::Helpers::NumberHelper)

這功能在現在的電腦構架很常見也常用啦,所以我就直接用了,也沒什麼測試,怕什麼!就這麼小小的一個常見功能......

直到,幾天前,有用戶跟我說,我的中英文介面中,數字是不一樣的,我一看,真是嚇到吃手手,同一個數字:

  • 中文 = 124.395K
  • English = 100K

這...... 嚇死人了,是那個偉大的程式,連數字都會搞錯?這很明顯的是進位有錯,很容易的就查到,問題發生在以下這行:

number_to_human(item.count, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })

妙的是,我左看右看,API 上看下看,都很正確啊,但是數字就是不對,問題很明顯的出在語言版本上,而剛好,我在 API 上有看到,這個 helper 可以在 i18n 中設定,死馬當活馬醫,在 I18n 中試試看設些不同的值,哇哈,變正確了!

問題解決了,但是我還是不知道,為什麼 Rails 會不尊照 hepler 中的設定,而一定要去讀 I18n中的設定,我也沒時間再查下去,說不定那天 Rails 又改了,但是應該要把這個解決方法記錄下來,不然我下次一定忘記,又要重查一遍,也可以發佈給大家做參考。

解法:

呼叫這 helper 就簡化到只要給變數就好:

number_to_human(item.count)

所有的設定都移到 I18n yml 中,這部分很奇怪,Rails 的文件中都找不到:

# for number_to_human
  number:
    human:
      decimal_units:
       format: "%n%u"
       units:
         unit: ""
         thousand: k
         million: M
         billion: B
         trillion: T
         quadrillion: Q
      format:
        delimiter: ','
        precision: 3
        significant: true
        strip_insignificant_zeros: true

這樣做,問題解決了,程式也清爽多了。 小小的提醒,YML 很重格式,複製貼上要小心!

好啦,老話一句,希望有幫助。

 


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
合計:550字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.