Search code examples
rubytestingcurrencymarathontesting

Silly Ruby Currency


Im using Jruby (thats ruby anyway, running under jvm :D ) with marathon test (a java swing app) and im having a little trouble handling currency numbers.

I dont use Rails (dont know if i can use rails even with marathon) and i dont know / didnt found HOW to convert a string to a decimal or a double.

My code with maraton is something like this

$saldoDisponivel = get_p("com.company.app.view.layout.objetos.JTextField1", "Text")

In other words, saldoDisponivel gets a string (ex: 3.232,20). I also have another string valor = "100,00" and when i do

$saldoDisponivel = $saldoDisponivel + valor 

Of course i get 3.232,20100,00 (add 2 strings right..lol)

I though ruby could handle those kind stuff more easly.. in java i would convert those on BigDecimails (using java.math.BigDecimal) but on pure Ruby, dont know how.

Thks in advance.


Solution

  • You should use BigDecimal in ruby as well so that you don't have any floating point errors:

    require 'bigdecimal'
    
    x = '3232.20'
    y = '100.00'
    
    xb = BigDecimal.new x
    yb = BigDecimal.new y
    
    r = xb + xy
    
    r.to_s('F')
    
    > r.to_s('F')
     => "3332.2"