Search code examples
javascriptcypressnumber-formatting

Passing parameters with comma values (European decimal format)


I have written a reusable function in Cypress:

fill_prices_ht_nt(until, AP, GP, AP_NT, new_bonus){
        this.add_range().click({force:true})
        this.range_until().type(until)
        this.ap().type(AP)
        this.gp().type(GP)
        this.ap_nt().type(AP_NT)
        this.new_bonus().type(new_bonus)

Now I want to use that function to type in values, but unfortunately I need to type in decimal values in European format (with comma instead of periods), like e.g. "9,35" or "6,47"

        pmmt.fill_prices_ht_nt(99999, 10, 9,35, 6,47, 100)

This is of course not working as Cypress/JS treats every comma as a separator.

Is there a somewhat easy workaround to this problem? Otherwise I will have to dump the reusable function and hard-code the values.


Solution

  • Here's one more option, using toLocaleString()

    fill_prices_ht_nt(until, AP, GP, AP_NT, new_bonus) {
      this.add_range().click({force:true})
      this.range_until().type(until)
      this.ap().type(AP.toLocaleString('de-DE'))  
      this.gp().type(GP.toLocaleString('de-DE'))   // AP.toLocaleString('de-DE') = 9,35
      this.ap_nt().type(AP_NT.toLocaleString('de-DE'))
      this.new_bonus().type(new_bonus.toLocaleString('de-DE'))
    

    In the test, pass with decimal and it will be converted as you .type()

    pmmt.fill_prices_ht_nt(99999, 10, 9.35, 6.47, 100)
    

    Or, you can add a method to set the format if you have other locale's to handle

    set_number_format(number_format) {
      this.number_format = number_format
    }
    
    fill_prices_ht_nt(until, AP, GP, AP_NT, new_bonus) {
      this.add_range().click({force:true})
      this.range_until().type(until)
      this.ap().type(AP.toLocaleString(this.number_format))  
      this.gp().type(GP.toLocaleString(this.number_format))
      this.ap_nt().type(AP_NT.toLocaleString(this.number_format))
      this.new_bonus().type(new_bonus.toLocaleString(this.number_format))
    

    In the test,

    pmmt.set_number_format('de-DE')
    pmmt.fill_prices_ht_nt(99999, 10, 9.35, 6.47, 100)
    ...
    pmmt.set_number_format('en-IN')
    pmmt.fill_prices_ht_nt(99999, 10, 9.35, 6.47, 100)