Silly Ruby Currency

286 Views Asked by At

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.

3

There are 3 best solutions below

1
Wes On BEST ANSWER

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" 
2
Pedro Rolo On
$saldoDisponivel=($saldoDisponivel.to_f + valor.to_f).to_s

Força nisso...

2
Dakshinamurthy Karra On

If you are more comfortable to use java BigDecimal, you can use java.math.BigDecimal directly from marathon scripts.

x = java.math.BigDecimal.new '5.0'
y = java.math.BigDecimal.new '10.0'
puts x.add(y)
=> 15.0