简体   繁体   English

使用Inputmask格式化百分比

[英]Formatting percentage using Inputmask

I'm using Herbots' InputMask, and it works well but I notice that it handles percentages such that a value of 0.4 with a mask of "0.00%" is formatted as "0.4%". 我正在使用Herbots的InputMask,但效果很好,但我注意到它可以处理百分比,因此掩码为“ 0.00%”的值为0.4的格式为“ 0.4%”。

Well, sure. 好吧,当然。 Makes sense. 说得通。 Except I'm dealing with the actual percentage value, which is a value between 0 and 1, so that 0.4 should show up as "40.00%" with said mask. 除非我要处理的实际百分比值是介于0和1之间的值,所以使用上述蒙版显示的0.4应该显示为“ 40.00%”。

I've run into this problem before (with other masking systems) and tried to fix it at the form level by multiplying the incoming value by 100 and dividing it on the way out, but that's an ugly thing. 我之前(使用其他遮罩系统)曾遇到过此问题,并试图通过将输入值乘以100并在出路时将其除以在表单级别进行修复,但这是一件丑陋的事情。 Is there something in InputMask (a preprocessor or custom hook) that would allow me to format the real value as a proper percentage? InputMask(预处理器或自定义钩子)中是否有某些东西可以让我将实际值格式化为适当的百分比?

OK, the way I worked around this was using the onBeforeMask and onUnMask functions. 好的,我的解决方法是使用onBeforeMask和onUnMask函数。 In Clojure, it was: 在Clojure中,它是:

:onBeforeMask (fn [value opts] (str (* 100 (cljs.reader/read-string value))))
:onUnMask (fn [maskedvalue unmaskedvalue] (str (/ unmaskedvalue 100)))

I'll still credit an alternative to massaging the data, if there is one. 如果有的话,我仍然相信一种替代数据的方法。 The key seems to be that onBeforeMask gives you a string and expects a string back, where onUnMask will give you a number (but still expects a string back). 关键似乎是onBeforeMask给您一个字符串并希望返回一个字符串,其中onUnMask将给您一个数字(但仍希望返回一个字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM