-4

So far I haven't found a solution to my problem.

I want to change a value.

So can convert value from $5,000,000 to 5000000 in java/kotlin?

  • I retrieve the data using jsoup/scraping, the data is a combination of several characters ($5,000,000). and I want to change it to 5000000 so that it can be formulated later. – nadhif Aini Aug 18 '21 at 23:00
  • `s = s.replaceAll("\\D", "")` will do it – g00se Aug 19 '21 at 08:34

1 Answers1

1

My "personal" approach is to try and figure out how you got the input in the in the first place. In this case, from Java, you'd probably use a NumberFormatter to format a numerical value to a String, so you might want to consider reversing it.

String text = "$5,000,000";
NumberFormat formatter = NumberFormat.getCurrencyInstance();
Number number = formatter.parse(text);
System.out.println(number.intValue());

Will print 5000000

Now, this will assume that the Locale the JVM is using makes use of $ and not say, pounds or yen, but you can seed the Locale when you call NumberFormat.getCurrencyInstance(), so that's one level of customisation you have.

Of course, you could just drop back to "$5,000,000".replace("$", "").replace(",", "") and then parse the result to an int, but I'm not a massive fan of it, but I'm peculiar that way

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • oh sorry, how about 5,000,000 to 5000000 without $? – nadhif Aini Aug 18 '21 at 23:15
  • i use `val number = (text).replace(",", "") println(number.toInt()) iShowLog("number: $number")` but the result stuck – nadhif Aini Aug 18 '21 at 23:26
  • i change from val number = (text).replace(",", "") to val number = text.replace(",", "") and resolved, thanks – nadhif Aini Aug 18 '21 at 23:41
  • You could consider generating a white/black list instead, such as "remove all non-numerical characters", something like [this](https://stackoverflow.com/questions/10372862/java-string-remove-all-non-numeric-characters-but-keep-the-decimal-separator) for example. But it depends on your needs – MadProgrammer Aug 19 '21 at 00:01