如何获取数字以输出小数而不是科学计数法

如何获取数字以输出小数而不是科学计数法

本文介绍了在jq中,如何获取数字以输出小数而不是科学计数法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JSON对象中,给定字符串"0.0000086900"作为键值对的值,如果我对此执行|tonumber,则返回8.69e-06.

In a JSON object, given the string "0.0000086900" as the value of a key-value pair, if I do |tonumber on this, 8.69e-06 gets returned.

如何确保仅返回小数?在上述情况下,该值为0.0000086900

How can I ensure that only decimals are ever returned?In the case above, this would be 0.0000086900

解决方案(基于以下Peak的代码段)

def to_decimal:
  def rpad(n): if (n > length) then . + ((n - length) * "0") else . end;
  def lpad(n): if (n > length) then ((n - length) * "0") + . else . end;

tostring
  | . as $s
  | [match( "(?<sgn>[+-]?)(?<left>[0-9]*)(?<p>\\.?)(?<right>[0-9]*)(?<e>[Ee]?)(?<exp>[+-]?[0-9]+)" )
      .captures[].string] as [$sgn, $left, $p, $right, $e, $exp]
  | if $e == "" then .
    else ($exp|tonumber) as $exp
    | ($left|length) as $len
    | if $exp < 0 then "0." + ($left | lpad(1 - $exp - $len)) + $right
      else ($left | rpad($exp - $len)) + "." + $right
      end
      | $sgn + .
    end;

推荐答案

不幸的是,jq当前无法修改JSON数字的表示形式.最好的办法是将其表示形式修改为字符串.这是可以做什么的简单说明.

Unfortunately there is currently no way in jq to modify the representation of JSON numbers as such; the best one can do is modify their representation as strings. Here is a simple illustration of what can be done.

to_decimal将JSON编号(或数字的有效JSON字符串表示形式,可能带有前导"+")作为输入,并将其转换为合适的字符串,例如:

to_decimal takes as input a JSON number (or a valid JSON string representation of a number, possibly with a leading "+") as input, and converts it into a suitable string, e.g.:

["0","1","-1","123","-123",".00000123","1230000","-.00000123","-0.123","0.123","0.001"]

产生:

[0,"0"]
["+1","1"]
[-1,"-1"]
[123,"123"]
[-123,"-123"]
[1.23e-06,".00000123"]
[1230000,"1230000"]
[-1.23e-06,"-.00000123"]
[-0.123,"-0.123"]
[0.123,"0.123"]
[0.001,"0.001"]

请注意,任何前导的"+"号被丢弃.

Notice that any leading "+" is dropped.

def to_decimal:
  def rpad(n): if (n > length) then . + ((n - length) * "0") else . end;
  def lpad(n): if (n > length) then ((n - length) * "0") + . else . end;

  tostring
  | . as $s
  | capture( "(?<sgn>[+-]?)(?<left>[0-9]*)(?<p>\\.?)(?<right>[0-9]*)(?<e>[Ee]?)(?<exp>[+-]?[0-9]+)" )
  | if .e == "" then (if .sgn == "+" then $s[1:] else $s end)
    else (.left|length) as $len
    | (.exp|tonumber) as $exp
    | (if .sgn == "-" then "-" else "" end ) as $sgn
    | if $exp < 0 then "." + (.left | lpad(1 - $exp - $len)) + .right
      else (.left | rpad($exp - $len)) + "." + .right
      end
      | $sgn + .
    end ;

这篇关于在jq中,如何获取数字以输出小数而不是科学计数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:44