a Quick help about Dollars & Cents in Java...

Discussion in 'Programming and Homework Questions' started by alexpre888, Oct 3, 2016.

  1. alexpre888

    alexpre888 Notebook Consultant

    Reputations:
    7
    Messages:
    157
    Likes Received:
    25
    Trophy Points:
    41
    so I was doing my program and I'm here learning java. I manage to run my program well...but I encountered something that bothers me.


    the display i put shows this:
    The Total Price: $3.684

    how do I make the program print something like $3.68 instead of $3.684?

    what should I add?

    my code is this:
    Code:
    package hw2;
    
    import java.util.Scanner;
    
    public class shippingcharge
    {
    
        public static void main(String[] args)
        {
            Scanner input = new Scanner(System.in);
            System.out.print("Enter Weight: ");
            double weight = input.nextDouble();
            System.out.print("Enter Shipping Charge per Pound as decimal starting .200: ");
            double shipping = input.nextDouble();
            if (weight > 1.0)
            System.out.println("Shipping Price: $" + (weight + 1 * shipping));
        } 
    
    }
    
     
  2. Jarhead

    Jarhead Systematic Love

    Reputations:
    4,816
    Messages:
    11,861
    Likes Received:
    2,466
    Trophy Points:
    581
    Well, if all you're looking for is truncation, you'd simply use DecimalFormat and specify that it rounds down:

    Code:
    double sprice = weight + 1 * shipping;
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.DOWN);
    if (weight > 1.0) System.out.println("Shipping Price: $" + df.format(sprice));
    
    Though some questions pop into my mind reading this:
    • Order of operations is probably giving you the wrong value, since weight + 1 * shipping is evaluated as weight + (1 * shipping) = weight + shipping, while I think you want (weight + 1) * shipping. It's best not to be ambiguous.
    • What's supposed to happen if weight <= 1.0? Seems the user can specify weight in the range [0.2, 1.0], which won't print the shipping price at all.
    • Ideally, you shouldn't use float/double for money values due to the issues in floating-point math. See http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency
     
Loading...

Share This Page