如何在AMP-html中将数字格式化为金钱?

时间:2018-02-06 00:05:30

标签: amp-html accelerated-mobile-page google-amp amp-bind

我有一些任意数字,在我的用例中介于1,000和1,000,000之间。我需要将此值格式化为显示值,其中显示为金钱。 I.e 1000 - > "$1,000"100000 - > "$100,000"

我遇到的问题是我的表情尺寸太大,AMP表达式太有限,因此按照我想要的方式格式化数字并不容易。我不能使用“.replace()”,或任何正则表达式,甚至使用基本条件似乎过于困难(似乎我甚至不能使用标准的三元运算符:a?b:c;)。

这就是我所拥有的

  //tells me how many digits i have
  amp-bind-macro#getLog10(arguments="num" expression="num.length - 1")

  //determines if the number should have a comma after it
  amp-bind-macro#numShouldHaveComma(arguments="log10" expression="log10%3==0 && log10!=0")

  //function to be invoked by Array.map()
  amp-bind-macro#formatNumber_map(arguments="char, ind, num" expression="(numShouldHaveComma(getLog10(round(num).toString().substr(ind+1))) && char+',') || char")

  //main formatter function (1000 -> 1,000)
  amp-bind-macro#formatNumber(arguments="num" expression="round(num).toString().split('').map((char,ind)=>formatNumber_map(char,ind, num)).join('')" )

  //adds $ and calls the formatter
  amp-bind-macro#formatMoney(arguments="val" expression="'$'+formatNumber(val)")

我有一个显示元素设置为当滑块的值改变时调用formatMoney,例如

<input type='range' on="input-throttled:AMP.setState({state:{mySlider:{value:event.value}}})" /> 

<div id='display-money' [text]="formatMoney(state.mySlider.value)">$1,000</div>

这种特殊的方式使我的堆栈大小为53,超过允许的最大值50。

我做round(num).toString()的原因是我似乎得到了不一致的类型 - 有时它是一个数字,有时它是一个字符串。这样,始终正确解析类型,并且不会抛出任何错误。

是否有一种更简单的方法可以将数字格式化为金钱(全部美元,数字以逗号分隔)?如果没有,我可以对现有代码做些什么来使其工作?

谢谢!

2 个答案:

答案 0 :(得分:0)

我提出的解决方案如下。

//determines how many "0's" there are.
amp-bind-macro#getLog10(arguments="num" expression="num.length - 1")

//determines if the number should have a comma after it
amp-bind-macro#numShouldHaveComma(arguments="log10" expression="log10%3==0 && log10!=0")

//helper function for formatNumber
amp-bind-macro#formatNumber_map(arguments="char, ind, numStr" expression="(numShouldHaveComma(getLog10(numStr.substr(ind)))) ? char+',' : char")

//main number formatter
amp-bind-macro#formatNumber(arguments="num, numStr" expression="numStr.split('').map((char,ind)=>formatNumber_map(char,ind, numStr)).join('')" )

//adds "$" and calls formatNumber
amp-bind-macro#formatMoney(arguments="val" expression="'$'+formatNumber(round(val), round(val).toString())")

本质上,我通过显式地将数字作为数字和字符串传递给下一个函数来简化表达式,这样我就不需要在每个宏中调用round(num).toString(),只有第一个。

答案 1 :(得分:-1)

对于整数情况class RegionAllocation{ int price; int alloQty; RegionAllocation(Product p) this.price = p.getPrice(); } RegionAllocation allocate(int a){ this.alloQty+=a; return this; } ,我建议在一个List<RegionAllocation> reg = new ArrayList(); for(Product p : products) { RegionAllocation r = new RegionAllocation(p); if(p.getRegion().equals("LDN") { r.allocate(0); } else{ r.allocate(p.getPrice()*5) } reg.add(r); } return reg; 中使用更紧凑的实现:

formatNumber

如果值仅是正数,则可以删除开头amp-bind-macro的{​​{1}}。

带小数位i posted here的完整变体。

相关问题