6

The following command achieve my goal by grepping BTC price from specific exchange.

curl -sS https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT | jq -r '.price'

the output will be for the moment 7222.25000000 but i would like to get it 7222.25

1
  • 2
    Note that generally, you should only use the curl tag if curl is an essential part of the problem. If you can download the file to save it on disk and run jq -r .price <myfile and get the same problem, curl isn't a necessary part of the problem. May 12, 2019 at 18:28

3 Answers 3

14

Pass the price through tonumber:

curl -sS 'https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT' |
jq -r '.price | tonumber'

This would convert the price from a string to a number, removing the trailing zeros. See the manual for jq.

1
  • Note that it seems to be doing the equivalent of printf %16g so you might lose some precision and numbers above 10 quadrillion would be represented with 1e16 notation and 0.00009 as 9e-05 for instance May 13, 2019 at 6:59
4

If you don't mind using a Bash builtin, printf might be the way to go:

curl -sS https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT | jq -r '.price' | xargs printf '%.2f'

This way you will keep the two trailing digits and get a rounding done as well.

2
  • 2
    xargs isn’t going to run the Bash builtin. May 13, 2019 at 6:23
  • @MichaelHomer you are right, xargs will run the printf binary and not the builtin.
    – Edward
    May 13, 2019 at 7:04
2

Awk is an option also

curl -sS https://api.binance.com/api/v1/ticker/price?symbol=BTCUSDT | jq -r '.price'  | awk '{printf "%.2f\n", $1}'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .