Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package test;
  2.  
  3. import java.math.BigDecimal;
  4. import java.math.RoundingMode;
  5. import java.util.ArrayList;
  6. import java.util.concurrent.atomic.AtomicInteger;
  7.  
  8. public class Test {
  9.  
  10.     public static ArrayList<Double> loadValues() {
  11.         ArrayList<Double> values = new ArrayList<Double>();
  12.         values.add(1726.014444);
  13.         values.add(1726.014496);
  14.         values.add(1726.024444449);
  15.         values.add(1726.024494444);
  16.         values.add(1726.023333333);
  17.         values.add(1726.029999999);
  18.         values.add(1726.045444444);
  19.         values.add(1726.0522929);
  20.         values.add(1726.12847120931);
  21.         values.add(1726.985379032);
  22.         return values;
  23.     }
  24.  
  25.     public static ArrayList<Double> validValues() {
  26.         ArrayList<Double> values = new ArrayList<Double>();
  27.         values.add(1726.01);
  28.         values.add(1726.02);
  29.         values.add(1726.03);
  30.         values.add(1726.03);
  31.         values.add(1726.02);
  32.         values.add(1726.03);
  33.         values.add(1726.05);
  34.         values.add(1726.05);
  35.         values.add(1726.13);
  36.         values.add(1726.99);
  37.         return values;
  38.     }
  39.  
  40.     public static void main(String[] args) {
  41.  
  42.         ArrayList<Double> values = loadValues();
  43.         AtomicInteger currentPosition = new AtomicInteger();
  44.  
  45.         for (Double val : values) {
  46.             double value = round(val, 2);
  47.             double mustValue = validValues().get(currentPosition.get());
  48.             if (value == value)
  49.                 System.out.println("Success");
  50.             else
  51.                 System.out.println("Value " + value + " must be " + mustValue);
  52.  
  53.             currentPosition.getAndIncrement();
  54.         }
  55.  
  56.     }
  57.  
  58.     private static double round(double numberToRound, int numberDecimals) {
  59.         if (numberDecimals < 0) throw new IllegalArgumentException();
  60.  
  61.         String stringValue = Double.toString(numberToRound);
  62.         String decimals = stringValue.split("\\.")[1];
  63.  
  64.         BigDecimal bd = new BigDecimal(stringValue);
  65.         for (int i = decimals.length() - 1; i >= numberDecimals; i--) {
  66.             bd = bd.setScale(i, RoundingMode.HALF_UP);
  67.         }
  68.  
  69.         return bd.doubleValue();
  70.     }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement