简体   繁体   中英

Rounding in Cypress

I want to compare a number from a form to a set number. The issue is that we have dozens of different systems and depending on the system the number can be displayed with 2 to 4 decimal places. So in one system the number is displayed as 11,1265, in another as 11,127 and in yet another as 11,13. Therefore I would like to found the number to decimal places before the assertion.

I have already found this this answer and and tried to implement the solution. Could not get it to work though as Cypress does not know .toFixed()

This is what I have tried so far:

  1. From answer 1
cy.get('#Client_rate_ap').then(res => {
                expect(res.toFixed(2)).to.equal('11,13')
})

This returns

TypeError
res.toFixed is not a function
  1. with cy.wrap()
 cy.get('#Client_rate_ap').then(res => {
                cy.wrap(res).toFixed(2).should('be.equal','11,13')
            })

and

 cy.get('#Client_rate_ap').then(res => {
                cy.wrap(res.toFixed(2)).should('be.equal','11,13')
            })

Both also return the error toFixed is not a function

{{edit}} Added element

This is the element with the value that I want to compare:

<input class="rate_ap tariff-connected-field" name="Client[rate_ap]" id="Client_rate_ap" type="text" value="11,1300">

You have to first convert your text to float and then apply .toFixed(2) . Something like:

cy.get('#Client_rate_ap')
  .invoke('val')
  .then((rate) => {
    expect(parseFloat(rate).toFixed(2)*1).to.equal(11.13)
  })

In case your prices are displayed in comma, then first you have to replace the comma with a decimal, in that case you can:

cy.get('#Client_rate_ap')
  .invoke('val')
  .then((rate) => {
    expect(parseFloat(rate.replace(',', '.')).toFixed(2)*1).to.equal(11.13)
  })

The simplest way using the answer you already found,

cy.get('#Client_rate_ap')
  .then(res => {
    expect(Math.abs(11.13 - res.replace(',','.'))).to.be.below(0.01)
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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