2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jqコマンドで、小数点以下n桁で切り捨てる

Last updated at Posted at 2021-01-05

やりたいこと

jqコマンドで「数値の小数点以下切り捨て」をするfloor関数ですが、
この関数は引数を取らず、「小数点以下n桁目で切り捨て」みたいな桁数指定ができません。

# NICTのWeb APIで現在時刻を取得
$ curl -s http://ntp-a1.nict.go.jp/cgi-bin/json
{
 "id": "ntp-a1.nict.go.jp",
 "it": 0.000,
 "st": 1609809594.456,
 "leap": 36,
 "next": 1483228800,
 "step": 1
}

# ミリ秒単位から秒単位に丸め
$ curl -s http://ntp-a1.nict.go.jp/cgi-bin/json | jq '.st | floor'
1609809594

# ミリ秒単位から0.1秒(100ミリ秒)単位に丸め
$ curl -s http://ntp-a1.nict.go.jp/cgi-bin/json | jq '.st | floor(1)'
jq: error: floor/1 is not defined at <top-level>, line 1:
.st | floor(1)      
jq: 1 compile error
(23) Failed writing body

何とかして、桁数指定の切り捨てをする方法です。

実現方法

floorの前後に掛け算割り算をして、桁数を調整します。
jqに限らず、一般的に使われる方法ですね。

小数点以下の桁数を調整

floor(1)的な奴です。
掛けて、floorして、割る。

# ミリ秒単位から0.1秒(100ミリ秒)単位に丸め
$ curl -s http://ntp-a1.nict.go.jp/cgi-bin/json | jq '.st *10|floor/10'
1609809594.4

小数点以上の桁数を調整

floor(-3)的な奴です。
割って、floorして、掛ける。

# ミリ秒単位から1000秒単位に丸め
$ curl -s http://ntp-a1.nict.go.jp/cgi-bin/json | jq '.st /1000|floor*1000'
1609809000

補足

ではまた~。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?