tags:

views:

63

answers:

4

When there is a string value such as 3.76 how can this be converted into a int cent value in this case 376.

I was thinking of using sprintf to remove the dot then convert to int but can't work out the syntax. How would I do this and is it the best way

A: 

removing the dot is rather easy:

cent.gsub!(/\./,"")

will remove the dot.

To get an int, simply call the integer constructor:

Integer(cent)

Of course you can combined the two operations:

Integer(cent.gsub!(/\./,""))
ennuikiller
I did this, pence = Integer(@card_balance)@card_balance is a string 3.76it comes up with an error invalid value for Integer: "3.76" (ArgumentError)
veccy
pence = @card_balance.gsub!(/\./,"").to_igot it to work
veccy
pence = Integer(@card_balalnce.gsub(/\./,"")) should work as well
ennuikiller
pence = (@card_balalnce.to_f * 100).to_i
Jonas Elfström
A: 

I assume you mean ANSI C and have a string value that you would like to convert into an int.

int cents = (atof(myString) * 100.0);

atof converts a string to a double (or float depending on compiler and platform), then just multiply with 100 to move the decimal pointer two steps right.

very simple :)

Max Kielland
I am using ruby
veccy
A: 

I think this is a bit more ruby-ish instead of calilng Integer(cent) and doing weird substitutions.

(cent * 100).to_i
Bitterzoet
`("3.76" * 100).to_i => 3` - Amsterdam, we have a problem!
Jonas Elfström
+2  A: 

Removing the dot only works if you always have two decimals, i.e. fine for "3.76", but not for "3.7" or even "3".

  • "3.76" => 376
  • "3.7" => 37 instead of 370
  • "3" => 3 instead of 300

Best solution might be to convert it to a float first, then multiply by 100 and only then turn it into an int. If you can have more then 2 decimals you'll need to decide on a rounding scheme. For instance:

("3.76".to_f * 100).to_i
Mario Menger
good to know. In this instance I am keeping to to decimals
veccy