1

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.

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
Leonardo
  • 35
  • 1
  • 4
  • Are these global variables? Why the dollar signs? – Wes Apr 15 '11 at 22:56
  • Yes, im using them cz im using it on a Module, and there is more than 1 metod on diferrent .rb that call it. Also i forgot to mention that my main string is something like 3.222,32 .. so.. i tried both answers and it didnt worked.. – Leonardo Apr 18 '11 at 16:44

3 Answers3

0

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" 
Wes
  • 6,455
  • 3
  • 22
  • 26
  • Worked like a charm.. i did x = x.gsub(".","") x = x.gsub(",",".") and y = y.gsub(".","") y = y.gsub(",",".") to work on the separetors and then used the bigdecimal.. thks – Leonardo Apr 18 '11 at 17:00
0

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

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
  • it works form float numbers... but it doesnt work with numbers like "3.222,32" .. i know i have to parse to remove the "dot" but i dont know how... i use this on java: DecimalFormat dff = (DecimalFormat) DecimalFormat.getInstance(); dff.setParseBigDecimal(true); BigDecimal valor = null; valor = (BigDecimal) dff.parse(Valor); – Leonardo Apr 18 '11 at 16:46
  • What ever you do in java, you can also do in Marathon scripts. – Dakshinamurthy Karra Apr 18 '11 at 17:18
-1
$saldoDisponivel=($saldoDisponivel.to_f + valor.to_f).to_s

Força nisso...

Pedro Rolo
  • 28,273
  • 12
  • 60
  • 94
  • This solution introduces floating point errors and by using the last step truncates decimal places: `('1.2'.to_f + '2.1'.to_f).to_i => 3` – Wes Apr 15 '11 at 23:10
  • The conversion to floating point will still introduce floating point addition errors. See the BigDecimal documentation for examples. – Wes Apr 15 '11 at 23:34