Come in this morning to meet a bug like this:
2 digits after the decimal point are not retained when the percentage is calculated, causing some results that cannot be divisible to be displayed too long
At first, I thought this was a very common bug, since Wxml supports simple operations within the page {{}}, I think I should also support the tofixed () method
So change the code and try
<text class= "Vote-item-data-percent" >{{(Item.vote_count/vote.data.voters_count). toFixed (2) *100}}%</ Text>
Run Result: not supported
Try it a different way.
Write a public numbertofixed function in the Util.js file and invoke it on the page.
Const NUMBERTOFIXED = n + = { n = n.tofixed (2) * + '% ' return n}module.exports = { Numbertofixed:number ToFixed}
Page Call
<text class= "Vote-item-data-percent" >{{util.numbertofixed (item.vote_count/vote.data.voters_count)}}%</ Text>
Run Result: Method not found, page not effectively introduced
Find the document and find that you can use the Wxs file to resolve
Document Address: https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxs/
The Wxs file is implemented to invoke the defined JavaScript function in the Wxml page
Specific ideas:
Use the Wxs file, then add the Numbertofix function to the Wxs file, and then introduce the Wxml file in the Wxs page that requires the Numbertofix method, and then you can call it through {{Numbertofix (persent)}}.
# Create a Numbertofix.wxs file, create a numbertofix function
var filter = { Numbertofix:function (value) { return value.tofixed (1) }}module.exports = { Numbertofix : Filter.numbertofix}
* * Introduce NUMBERTOFIX.WXS file in a page that needs to use the Numbertofix function
<wxs module= "Filter" src= ". /.. /utils/numbertofix.wxs "></wxs>
3# calls can be
<text class= "Vote-item-data-percent" >{{filter.numbertofix (item.vote_count/vote.data.voters_count*100)}}% </text>
Run result: normal, Bug resolved
Applet: How to call JavaScript functions in the Wxml page