Home > Enterprise >  How to add 2 decimals on a double
How to add 2 decimals on a double

Time:12-01

I have a rails web app that uses react on the front end. I created a migration to have the precision => 8, scale => 2, and default => 0.00

class ChangeNumericFieldInTeamDonations < ActiveRecord::Migration[6.1]
  def self.up
    change_column :team_donations, :unit_cost, :decimal, :precision => 8, :scale => 2, :default => '0.00'
  end
end

This works, but as I go to the presentation layer, and use react, I pass my props in as follows:

export default function DonationsEdit(props) {
  const [donation, setDonation] = useState(props.donation);
  const [saving, setSaving] = useState(false);

*** removed rows to limit size of write up ***


          <div className="row">
            <div className="col-md-12">
              <div className="form-group">
                <label htmlFor="unit_cost">Unit Cost</label>
                <input className="form-control" placeholder="0.00" type="number" step="0.01" name="unit_cost" id="unit_cost"
                  value={donation.unit_cost} 
                  onChange={e => {
                    const val = e.target.value;
                    setDonation(donation => {
                      return { ...donation, unit_cost: val }
                    });
                  }}
                />
              </div>
            </div>
          </div>
    </React.Fragment>
  );
}

DonationsEdit.propTypes = {
  donation: PropTypes.object
};

How can I ensure that the form starts with the decimal type 0.00 instead of 0.0?

This is a price, and I don't like having it with only one decimal place because it looks wrong.

I tried to create a function using '%.2f' % donation.unit_cost, but I can't figure out how to get that to work with the return render - any ideas would be helpful. Thanks!

CodePudding user response:

You could use toFixed function

const hello = 0.0
// Log to console
console.log(hello.toFixed(2))

read more about it in here

CodePudding user response:

You can use attribute input PATTERN of HTML

ref: https://www.w3schools.com/tags/att_input_pattern.asp

<input className="form-control" pattern="[0-9]\.[0-9][0-9]" placeholder="0.00" type="number" step="0.01" name="unit_cost" id="unit_cost"  />
  • Related