1

I need to be able to capture decimals with only 2 digits after the decimal

point java, tried this

This is my code , i need to know be able to read with 2 decimal places

package project.pkg1;

import javax.swing.JOptionPane;

/**
 * @author Maria Andrea Quintana 4891405 *
 * @author Salvador Frias
 */
public class Project1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        String s1 = JOptionPane.showInputDialog("Enter the purchase amount");


        if (s1 == null) {
            JOptionPane.showMessageDialog(null, "You must enter a valid integer");
            System.exit(0);
        }

        if (s1.isEmpty()) {
            JOptionPane.showMessageDialog(null, "You must enter a valid integer");
            System.exit(0);
        }

        for (int i = 0; i < s1.length(); i = i + 1) {
            if (!Character.isDigit(s1.charAt(i))) {
                JOptionPane.showMessageDialog(null, "You must enter an integer value");
                System.exit(0);
            }
        }
hhhh
  • 137
  • 2
  • 11

4 Answers4

1

You can use a DecimalFormat to format your double:

    double input = 455.1689;

    DecimalFormat df = new DecimalFormat("#.00");

    System.out.println(df.format(input));

Look at this question dealing with the same problem.

EDIT 2:
Delete the for loop and put this code in its place

    double input = Double.parseDouble(s1);
    DecimalFormat df = new DecimalFormat("#.00");

    s1 = df.format(input);
Community
  • 1
  • 1
Oliver-R
  • 163
  • 1
  • 9
  • i don t get it, i want to modify what i have, so should i write another if for that one? – hhhh Sep 19 '15 at 08:18
  • Could you tell us what s1 is? A TextField? A String? – Oliver-R Sep 19 '15 at 08:26
  • a string sorry... s1 is the amount of the sale – hhhh Sep 19 '15 at 08:29
  • should i name input amountGiven, or the name i gave it for the other calculations/.? – hhhh Sep 19 '15 at 08:40
  • Could you edit your question and post all of your code? That would help us see what you are trying to do. – Oliver-R Sep 19 '15 at 08:41
  • can i modify this ===> for (int i = 0; i < s1.length(); i = i + 1) { if (!Character.isDigit(s1.charAt(i))) { JOptionPane.showMessageDialog(null, "You must enter an integer value"); System.exit(0); } } – hhhh Sep 19 '15 at 08:41
  • i did, take a look now – hhhh Sep 19 '15 at 08:44
  • If you input something like 23, should it accept it? Or should it always have a decimal – Oliver-R Sep 19 '15 at 08:46
  • it work perfect with everything but, even after i receive change, but when i input let s say 2.50 it does not take it – hhhh Sep 19 '15 at 08:51
  • where should i place it, before or afte the if statements? – hhhh Sep 19 '15 at 08:53
  • After the if statements, where the for loop is right now – Oliver-R Sep 19 '15 at 08:53
  • oh, youmean replace the for loop ? – hhhh Sep 19 '15 at 08:56
  • String s1 = JOptionPane.showInputDialog("Enter the purchase amount"); if (s1 == null) { JOptionPane.showMessageDialog(null, "You must enter a valid integer"); System.exit(0); } if (s1.isEmpty()) { JOptionPane.showMessageDialog(null, "You must enter a valid integer"); System.exit(0); } double input = Double.parseDouble(s1); DecimalFormat df = new DecimalFormat("#.00"); s1 = df.format(input); } double purchaseAmount = Double.parseDouble(s1); – hhhh Sep 19 '15 at 09:03
  • you are awesome Oliver – hhhh Sep 19 '15 at 09:08
  • thank you soooooooo much, i have been working on this for the past 24 to 36 hs lol – hhhh Sep 19 '15 at 09:09
  • No problem, if the answer is right, click the green arrow on my answer to accept it – Oliver-R Sep 19 '15 at 09:10
  • now if i put letter it doesn t work, is there any way to take what the loop did for letters and symbols – hhhh Sep 19 '15 at 09:12
  • Ohhhhh ok i see what u did.... Omg oliver, i have learned more today than in 3 weeks of class.... cannot thank you enoughhhhhhh – hhhh Sep 19 '15 at 09:23
  • idk how now it doesn t take decimals, is that even possible. after it was working before? – hhhh Sep 19 '15 at 17:51
0

Try like this:

s1 is your text or string value:

   String s=String.format("output: %.2f", s1);
                System.out.println(s);
soorapadman
  • 4,451
  • 7
  • 35
  • 47
  • i just don t know how to do it in terms of s1. – hhhh Sep 19 '15 at 08:21
  • i want to modify this, for (int i = 0; i < s1.length(); i = i + 1) { if (!Character.isDigit(s1.charAt(i))) { JOptionPane.showMessageDialog(null, "You must enter an integer value"); System.exit(0); } } – hhhh Sep 19 '15 at 08:22
  • so what you are telling is from string you want only two digit after a decimal is that correct? – soorapadman Sep 19 '15 at 08:26
  • i posted my whole code, edited my question, take a look and tell me if you see what should i modify please – hhhh Sep 19 '15 at 08:45
0

Since you are working with money which can be of different currency unit's. I would suggest you to take a look at Moneta API

Maven dependency to add:

<!-- Moneta -->
<dependency>
   <groupId>org.javamoney</groupId>
      <artifactId>moneta</artifactId>
    <version>0.9</version>
</dependency>

Example:

MonetaryAmount monetaryAmount = MonetaryAmounts.getDefaultAmountFactory()
.setNumber(3.45)
.setCurrency("USD")
.create();

System.out.println("EXACT MONETARY VALUE: "+monetaryAmount.getNumber().doubleValueExact()); // 3.45
System.out.println("VALUE AFTER DECIMAL: "+monetaryAmount.getNumber().getAmountFractionNumerator()); // 45

Edit:

If you are allowed to use regular expressions, I think this is what you are looking for

String s1 = JOptionPane.showInputDialog("Enter the purchase amount");
double d = 0.0;

int counter = 0;
Matcher match = Pattern.compile("[aA-zZ]+").matcher(s1);
while (match.find()) {
    counter++;
}

if((!s1.isEmpty()) && (s1.trim().length()!=0) && (counter == 0)){
    if(s1.contains(".")){
        String[] strings = s1.split("\\.");
        if (strings[1].length() > 2) {
            System.out.println("Maximum 2 places allowed after decimal.");
            System.exit(0);
        }
    }
    d = Double.parseDouble(s1);
}else if(counter > 0){
    System.out.println("Only numeric values are allowed");
    System.exit(0);
}
System.out.println("Expected input retrieved: " + d);
Sandeep Chatterjee
  • 3,220
  • 9
  • 31
  • 47
  • problem is...we have not seen that yet. and i cannot use stuff we have not seen in class. this is the 3rd week so stuff is pretty basic. – hhhh Sep 19 '15 at 08:36
  • Yes, something like that, thank you so much for taking the time to help – hhhh Sep 19 '15 at 15:51
  • 1
    That's ok. You could even refactor validations into individual methods and test them indvidually. Take a look at this [refactored code](https://pastebin.com/g1RQJ82z) and try running it, validate for different test cases and enhance accordingly. Good luck. – Sandeep Chatterjee Sep 19 '15 at 17:47
0

Solved,

      String s1 = JOptionPane.showInputDialog("Enter the purchase amount");

    if (s1 == null) {
        JOptionPane.showMessageDialog(null, "You must enter a valid integer");
        System.exit(0);
    }

    if (s1.isEmpty()) {
        JOptionPane.showMessageDialog(null, "You must enter a valid integer");
        System.exit(0);
    }

    if (s1.equals("0")) {
        JOptionPane.showMessageDialog(null, "You must enter a valid integer");
        System.exit(0);
    }

    if (s1.matches("[a-zA-Z]+")) {
        JOptionPane.showMessageDialog(null, "You must enter a valid integer");
        System.exit(0);
    }

    double input = Double.parseDouble(s1);
    DecimalFormat df = new DecimalFormat("#.00");

    s1 = df.format(input);
hhhh
  • 137
  • 2
  • 11