1

Hi i have a CSV file that contains rows like this

Jacop , "Assistant",150,75

i want to convert 3rd column to 150.75 in java

Should i write a function for this .Or is there another way?

thanks

jacop41
  • 152
  • 7
  • 25
  • This answer explains how to capture the last occurrence in a line using a regex (substitute): http://stackoverflow.com/questions/4094024/how-to-replace-last-dot-in-a-string-using-a-regular-expression. This answer explains how to convert a string to a number in Java: http://stackoverflow.com/questions/1097332/convert-a-string-to-number-java – Kai Sternad Jan 28 '11 at 21:55

3 Answers3

1

Quick idea:

  • get that value as String
  • replace "," with "." in String
  • try to parse double with Double.parseDouble
Xorty
  • 18,367
  • 27
  • 104
  • 155
1

UBe careful of floating point arithmetic errors, but this is the right idea:

int a = Integer.valueOf("150"); // Since your numbers are coming from a CSV
int b = Integer.valueOf("75");

double c = c = (a * 100 + b) / 100.0;
=> 150.75

Note, the value if 100 is there assuming that your number to the right of the decimal is always two digits. So, if that isn't constant, don't use this answer.

Jeremy
  • 22,188
  • 4
  • 68
  • 81
0

Simple regular expression search and replace in your text file (using sed or whatever) to convert the last comma to a decimal point should work fine.

Then use opencsv to pull it all in:

http://opencsv.sourceforge.net/

kvista
  • 5,039
  • 1
  • 23
  • 25