Parsing a currency String in java
Asked Answered
C

3

10

Suppose I'm supplied with a String which is like "$123,456,56.25" or "123'456.67" or something similar to this (with digits and a decimal point and some seperator like , or ' or something else which is not predictable). I need to write a method which takes an argument like the one above and returns a String like "12345656.25" or "123456.67" respectively.

Could you please suggest the most efficient and readable code to achieve this?

Note: I'm aware of going through each indexes and checking for whether its retunrs true for Character.isDigit(charAtInedx) or if(charAtInedx == '.') I'm looking for a more optimized solution both in terms of efficiency and readability

Thanks.

Clam answered 16/5, 2011 at 11:10 Comment(4)
formatting is when you try to output a string. "decoding" a given string is usually called parsing.Sexivalent
@Sexivalent Thanks a lot for the info. I never thought that way.Clam
Do you need to consider formats like 123.456.67 or 123.456,67?Mccollough
I'm trying to refactor a piece of code which reads ` StringBuffer buffer = new String Buffer (stringInput);for ( int i=0; i<buffer.length; i++){ if(buffer.charAt(i)) != '0' && buffer.charAt(i) != '1'` ..... etc && buffer.charAt(i) != '.'{ buffer.deleteCharAt(i); i= i-1;}. So I assume any code suggestion would be better than than current implementation.Clam
A
19
String newStr = oldStr.replaceAll("[^\\d.]+", "")

This will drop any character that is not either a digit or a period

Altair answered 16/5, 2011 at 11:14 Comment(6)
@jarnbjo Please re-read the question: with digits and a decimal point and some seperatorAltair
Even I'm not sure about the variety of inputs this method may receive. But looking at the current code I'm sure the regular expression you suggested would suffice. Thanks.Clam
00000000042. will pass that RegEx and that doesn't look like a valid currency value to me.Therese
@Therese you're absolutely right. This is not a universal currency fixer, but a regex for the specific situation the OP mentioned.Altair
Sure. But reading op's title it's clear what the intent here is, and I don't think allowing a string of fifty decimal points is helpful. It may technically satisfy what op said but a better answer would have provided some/additional guidance IMO.Therese
@Therese feel free to provide that answerAltair
M
8

If you want to handle monetary values correctly, you will want to have a look at the NumberFormat class, specifically for your case NumberFormat.parse(String). The following article also discusses the problems (and solutions) to handling money in Java:

http://www.javapractices.com/topic/TopicAction.do?Id=13

Other related classes include: Currency and of course BigDecimal.

Mccollough answered 16/5, 2011 at 11:24 Comment(0)
J
0

To parse a currency instance in Java, you can use the NumberFormat.getCurrencyInstance object. For example:

import java.text.NumberFormat;
import java.text.ParseException;

public class Main {
    public static void main(String[] args) throws ParseException {
        NumberFormat currency = NumberFormat.getCurrencyInstance(); // get the currency formatter
        String price = currency.format(19292.282); // format as a currency
        System.out.println(price); // $19,292.28

        Number parsePrice = currency.parse(price);
        System.out.println(parsePrice); // 19292.28
    }
}

Keep in mind that this is just a quick example, and you would need to account for exceptions as well.

Jataka answered 3/4 at 5:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.