Skip to content
Snippets Groups Projects
PriceEditor.js 1.24 KiB
Newer Older
  • Learn to ignore specific revisions
  • meskio's avatar
    meskio committed
    import React, { useState } from "react";
    import { Form } from "react-bootstrap";
    
    function str2price(str) {
    
      let negative = false;
      if (str[0] === "-") {
        str = str.substring(1);
        negative = true;
      }
    
    
    meskio's avatar
    meskio committed
      let value = str.split(",");
      let cents = 0;
    
      if (value.length > 2) {
        return NaN;
      }
    
      if (value.length === 1) {
        value = str.split(".");
      }
    
      if (value.length === 2) {
        if (value[1].length > 2) {
          return NaN;
        }
    
        cents = parseInt(value[1]);
        if (value[1].length === 1) {
          cents = cents * 10;
        }
        if (cents > 99) {
          return NaN;
        }
      }
    
    
      let price = parseInt(value[0]) * 100 + cents;
      if (negative) {
        price = -price;
      }
      return price;
    
    meskio's avatar
    meskio committed
    function price2str(price) {
      let centStr = (price % 100).toString();
      if (centStr.length === 1) {
        centStr = "0" + centStr;
    
    meskio's avatar
    meskio committed
      }
    
    meskio's avatar
    meskio committed
      return Math.floor(price / 100) + "," + centStr;
    }
    
    function PriceEditor(props) {
      const [value, setValue] = useState(price2str(props.value));
    
    meskio's avatar
    meskio committed
    
      const change = (e) => {
        setValue(e.target.value);
        const price = str2price(e.target.value);
        props.onChange(price);
      };
    
    
    meskio's avatar
    meskio committed
      const invalid = isNaN(props.value);
    
    
    meskio's avatar
    meskio committed
      return <Form.Control value={value} onChange={change} isInvalid={invalid} />;
    }
    
    export default PriceEditor;