string to int currency formatting
When there is a string value such as 3.76 how can this be converted into a int cent value in this case 376开发者_JAVA百科.
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
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!(/\./,""))
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 :)
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 using round. If you can have more then 2 decimals you'll need to decide on a rounding scheme. For instance:
("3.76".to_f * 100.0).round
Note that converting from a float to an int using to_i isn't accurate, as mentioned by Clint in a comment to this answer.
I think this is a bit more ruby-ish instead of calilng Integer(cent) and doing weird substitutions.
(cent * 100).to_i
精彩评论