处理用户货币输入

时间:2018-03-23 21:19:57

标签: javascript react-native

我目前正在寻找一种优雅的解决方案来实现用户的货币输入。 目标是输入感觉自然,即:例如,如果你输入' 1'现金价值应为:' 0.01 $'。如果您输入另一个' 1'价值应为:< 0.11 $'等等。

在我的特定解决方案中,输入由自定义输入按钮处理,如Windows计算器上的按钮。

目前我已经像这样处理了(解决方案是复杂的,但我只是没有找到一个简单的解决方案)

组件状态:

this.state = {
 cash: 0.00,
};
this.cashInt = 0; //represents the value before the decimal point
this.cashFloat1 = 0; //represenst the first decimal place
this.cashFloat2 = 0; //represents the second decimal place

自定义输入按钮:

<Button
  title={'1'}
  onPress={() => { this.addNumber(1); }}
/>

addNumber功能:

addNumber = (number) => {
 if (this.cashInt === 0 && this.cashFloat1 === 0 && this.cashFloat2 === 0) {
   this.cashFloat2 = number;
   this.newCash = 
   parseFloat(`${this.cashInt}.${this.cashFloat1}${this.cashFloat2}`);
   this.setState({ cash: this.newCash }); 
} else if (this.cashInt === 0 && this.cashFloat1 === 0 && this.cashFloat2 !== 0) {
   this.cashFloat1 = this.cashFloat2;
   this.cashFloat2 = number;
   this.newCash = parseFloat(`${this.cashInt}.${this.cashFloat1}${this.cashFloat2}`);
   this.setState({ cash: this.newCash });
} else if (this.cashInt === 0 && this.cashFloat1 !== 0 && this.cashFloat2 !== 0) {
   this.cashInt = this.cashFloat1;
   this.cashFloat1 = this.cashFloat2;
   this.cashFloat2 = number;
   this.newCash = parseFloat(`${this.cashInt}.${this.cashFloat1}${this.cashFloat2}`);
   this.setState({ cash: this.newCash });
} else if (this.cashInt !== 0 && this.cashFloat1 !== 0 && this.cashFloat2 !== 0) {
   this.cashInt = +(this.cashInt.toString() + this.cashFloat1.toString());
   this.cashFloat1 = this.cashFloat2;
   this.cashFloat2 = number;
   this.newCash = parseFloat(`${this.cashInt}.${this.cashFloat1}${this.cashFloat2}`);
   this.setState({ cash: this.newCash });
  }
};

所以基本上我正在做的事情(因为我无法找到任何其他方法使其工作)是每次输入新数字时,数字将代替第二个小数位,而前一个值将偏移到浮动的左侧。

一个尚未处理但应在解决方案中处理的特殊情况是值&#39;#,两个零接一个,以便用户更快地输入数百个。

还有其他方法可以达到这个目的吗?一个答案将不胜感激! 非常感谢

1 个答案:

答案 0 :(得分:0)

toLocaleString()可让您将数字转换为所需的货币格式 我的理解是你不希望用户输入,然后你可以简单地将数字除以100 这符合您的期望吗?

function currency(numStr) {
  let num = parseInt(numStr.replace(/[$,.]/g, ''));
  if (isNaN(num)) { num = 0; }
  else { num = num / 100; }
  return num.toLocaleString('en', { minimumFractionDigits: 2, style: 'currency', currency: 'USD' });
}

console.log(currency("a"));
console.log(currency("1"));
console.log(currency("10"));
console.log(currency("123456"));
console.log(currency("$1.00"));
console.log(currency("$10.00"));
console.log(currency("$1,234.56"));