Converting a price string into an integer - java

I need to convert prices into integers, like such:
(String) 12,000 to (int) 12000
245.00 to (int) 245
How can I do this?

Use NumberFormat.getCurrencyInstance():
NumberFormat nf = NumberFormat.getCurrencyInstance(); // Use Locale?
int[] ints = new int[strings.length];
for(int i = 0 ; i < strings.length ; ++i) {
ints[i] = nf.parse(strings[i]).intValue();
}

Much shorter than the other solutions:
public static int parseStringToInt(String s){
s = s.replaceAll(",", ""); //remove commas
return (int)Math.round(Double.parseDouble(s)); //return rounded double cast to int
}
Use it like so:
public static void main(String[] args) {
String[] m = {"12,000", "245.67"};
for (String s : m){
System.out.println(parseStringToInt(s));
}
}

public static int convertDoubleToInt(double d){
//rounds off to the nearest 100
long l = Math.round(d);
int i = (int) l;
return i;
}
public static double convertCommaDoubleToInt(String s) throws ParseException{
NumberFormat nf = NumberFormat.getInstance(Locale.US);
Number number = nf.parse(s);
return number.doubleValue();
}
public static void main(String[] args) throws ParseException {
String[] moneys = {"12,000", "245.76"};
for(String n: moneys){
Double d = convertCommaDoubleToInt(n);//first remove the comma, if there
System.out.println(convertDoubleToInt(d)); //then convert double into int
}
}

Related

Calculator for metric distance from an expression that contains different scales

public enum Operator {
PLUS("+"),
MINUS("-");
private final String operator;
Operator(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator getByValue(String operator) {
for (Operator operatorEnum : Operator.values()) {
if (operatorEnum.getOperator().equals(operator)) {
return operatorEnum;
}
}
throw new IllegalArgumentException("Invalid value");
}
}
//////////
public enum MetricConvertor {
m(1000),
cm(10),
mm(1),
km(1000000),
dm(100);
private int scale;
MetricConvertor(int scale) {
this.scale = scale;
}
public int getScale() {
return scale;
}
}
/////////
public class Application {
public static void main(String[] args) {
int scale = MetricConvertor.valueOf("m").getScale();
}
I wan to create a calculator that is capable of computing a metric distance value from an expression that contains different scales and systems.
Output should be specified by the user.
Only Addition and subtraction is allowed.
Output is in lowest unit.
Expression: 10 cm + 1 m - 10 mm
Result: 1090 mm
I am stuck at this point, how can I add or substract the values for a list and convert them at the lowest scale sistem( eg above mm, but it can be dm if are added for example dm + m + km)
Here is solution
split each string by add/minus and add it to appropriate list
split number and metric in each list(can use matcher) and sum it
result = sumAdd - sumMinus(mm).
Please optimize it, because i don't have time to optimize this code, I need to go to bed :D
Result is in mm, so you have to get lowest metric and recaculate it(leave it to you).
private static int caculator(String exp) {
List<String> addList = new ArrayList<>();
List<String> minusList = new ArrayList<>();
int checkPoint = 0;
boolean op = true;//default first value is plus
// Split string with add/minus
for (int i = 1; i < exp.length(); i++) {
String s = exp.substring(i, i + 1);
if (Operator.PLUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = true;
continue;
}
if (Operator.MINUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = false;
continue;
}
}
// Add last string
checkOperator(addList, minusList, op, exp.substring(checkPoint).trim());
// Get sum each list
int sumAdd = sumList(addList);
int sumMinus = sumList(minusList);
return sumAdd - sumMinus;
}
//sum a list
private static int sumList(List<String> addList) {
int sum = 0;
for (String s: addList) {
String[] arr = s.split(" ");
int value = Integer.parseInt(arr[0]);
int scale = MetricConvertor.valueOf(arr[1]).getScale();
sum += value * scale;
}
return sum;
}
// check operator to put into approriate list
private static void checkOperator(List<String> addList, List<String> minusList, boolean op, String substring) {
if (op) {
addList.add(substring);
} else {
minusList.add(substring);
}
}

How do I convert decimal 75.95 to 7595 in Java?

I have a program in which i need to convert double 75.95 to normal integer 7595. How do I write the actual program?
My code is:
class test5 {
public static void main(String args[]) {
double d = 75.95;
System.out.println("Price before converting = "+d);
int i = (int)d;
System.out.println("(float)d = "+i);
}
}
Any particular reason why multiplying by 100 wouldn't work?
class test5 {
public static void main(String args[]) {
double d = 75.95;
System.out.println("Price before converting = "+d);
long i = Math.round(d * 100);
System.out.println("(float)d = "+i);
}
}
You have to be careful with rounding errors. See: Losing precision converting from int to double in java
Now my code is this and its working :) thanks all of you :)
class test5
{
public static void main(String args[])
{
double d = 75.95;
{
System.out.println("Price before converting = "+d);
int i = (int)(d*100);
System.out.println("Answer after converting = "+i);
}
}
}
You can multiply by a constant 100 (if there are only, and always two decimal points). If there are more, you could use String.valueOf(double) and remove the '.' and call a double a double (not a float). Something like
double d = 75.95;
// int val = (int) (d * 100); // <-- or this.
String str = String.valueOf(d).replace(".", "");
int val = Integer.valueOf(str);
System.out.printf("(double)%f = (int)%d%n", d, val);
Which outputs
(double)75.950000 = (int)7595

java.lang.NullPointerException in two related java class

I implemented two java classes to solve the percolation problem but it throws the following exception
java.lang.NullPointerException
at PercolationStats.<init>(PercolationStats.java:24)
at PercolationStats.main(PercolationStats.java:54)
Program:
public class PercolationStats {
int t=0;
double[] sample_threshold;
Percolation B;
int N1;
public PercolationStats(int N, int T) {
t=T;
N1 = N;
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
public double mean() {
double sum = 0.0;
for(int i=0;i<N1;i++) {
sum += sample_threshold[i];
}
return sum/t;
}
public double stddev() {
double sum = 0.0;
double u = mean();
for(int i=0;i<N1;i++) {
sum += (sample_threshold[i]-u)*(sample_threshold[i]-u);
}
return sum/(t-1);
}
public double confidenceLo() {
return mean()-((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public double confidenceHi() {
return mean()+((1.96*Math.sqrt(stddev()))/(Math.sqrt(t)));
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int T = Integer.parseInt(args[1]);
PercolationStats C=new PercolationStats(N,T);
double mean=C.mean();
double stddev = C.stddev();
double confidenceLo = C.confidenceLo();
double confidenceHi = C.confidenceHi();
System.out.println("mean = "+mean);
System.out.println("stddev = "+stddev);
System.out.println("95% confidence interval = "+confidenceLo+", "+confidenceHi);
}
}
You never initialized double[] sample_threshold;. Hence it is null.
Java will indeed fill a double[] with 0.0 once it is initialized to a known size. You must initialize the array first:
public PercolationStats(int N, int T) {
t=T;
N1 = N;
sample_threshold[i] = new double[T]; // add this line
int number_of_open=0;
for(int i=0;i<T;i++) {
B=new Percolation(N1);
while(!B.percolates()) {
double r1 = Math.random();
int open_i = (int)(r1*N1);
double r2 = Math.random();
int open_j = (int)(r2*N1);
B.open(open_i,open_j);
}
for(int k=0;k<N1;k++) {
for(int j=0;j<N1;j++) {
if(B.isOpen(k, j))
number_of_open++;
}
sample_threshold[i] = (number_of_open*1.0)/N1;
}
}
}
here at 3rd line where you've written double[] sample_threshold;
instead just write double[] sample_threshold= new double[5000];
meaning just initalize the array. Then when you use it in for loop java will only consider the arrays for the times your for loop loops.

list of doubles, print a String

I have a list of values (Weather data), the people who wrote the list used the value "9999" when they did not have a value to report. I imported the text file and used the following code to take the data, and edit it:
import java.io.*;
import java.util.*;
public class weatherData {
public static void main(String[] args)
throws FileNotFoundException{
Scanner input = new Scanner(new File("PortlandWeather2011.txt"));
processData(input);
}
public static void processData (Scanner stats){
String head = stats.nextLine();
String head2 = stats.nextLine();
System.out.println(head);
System.out.println(head2);
while(stats.hasNextLine()){
String dataLine = stats.nextLine();
Scanner dataScan = new Scanner(dataLine);
String station = null;
String date = null;
double prcp = 0;
double snow = 0;
double snwd = 0;
double tmax = 0;
double tmin = 0;
while(dataScan.hasNext()){
station = dataScan.next();
date = dataScan.next();
prcp = dataScan.nextInt();
snow = dataScan.nextInt();
snwd = dataScan.nextInt();
tmax = dataScan.nextInt();
tmin = dataScan.nextInt();
System.out.printf("%17s %10s %8.1f %8.1f %8.1f %8.1f %8.1f \n", station, date(date), prcp(prcp), inch(snow), inch(snwd), temp(tmax), temp(tmin));
}
}
}
public static String date(String theDate){
String dateData = theDate;
String a = dateData.substring(4,6);
String b = dateData.substring(6,8);
String c = dateData.substring(0,4);
String finalDate = a + "/" + b + "/" + c;
return finalDate;
}
public static double prcp(double thePrcp){
double a = (thePrcp * 0.1) / 25.4;
return a;
}
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = 9999;
}
return a;
}
public static double temp(double theTemp){
double a = ((0.10 * theTemp) * 9/5 + 32);
return a;
}
}
The problem I am having is taking the values and checking for all times "9999" comes up, and printing out "----". I don't know how to take in a value of type double, and print out a String.
This code takes the values and checks for the value 9999, and does nothing with it. This is where my problem is:
public static double inch(double theInch){
double a = theInch / 25.4;
if(theInch == 9999){
a = "----";
}
return a;
}
I'm sorry if I put to much information into this question. If you need me to clarify just ask. Thanks for any help!
You need to modify your inch function to return a string, not a double.
public static String inch(double theInch){
if(theInch == 9999){
return "----";
}
return Double.toString(theInch/25.4);
}
I think the first problem might be that you're reading all the values from the Scanner as int instead of doubles. For example, based on your System.out.println() statement, I think you should actually be reading the following data types...
prcp = dataScan.nextDouble();
snow = dataScan.nextDouble();
snwd = dataScan.nextDouble();
tmax = dataScan.nextDouble();
tmin = dataScan.nextDouble();
Also, seeing as though the inch() method is only going to be used in the System.out.println() line, you'll need to change it to a String as the return type...
public String inch(double theInch){
if (theInch == 9999){
return "----";
}
return ""+(theInch/25.4);
}

Trim Double to 2 decimal places

should be an easy one. I originally was gonna do this in javascript but have to do it prior to setting to the form in my handler page. Anyway I need to make these values have 2 decimal places. Ex 219333.5888888 needs to be 219333.58. Is there a trim function or something?
form.setUnitRepairCost(Double.toString(jobPlanBean.getUnitTotalCost())); //UNIT REPAIR COST
form.setUnitMaterialCost(Double.toString(jobPlanBean.getUnitTotalMaterialCost())); //UNIT MATERIAL COST
here is the simple example to format the decimal value
import java.text.*;
public class DecimalPlaces {
public static void main(String[] args) {
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
}
}
multiply the double by 100.0 and cast this to an int then take that int and cast it to a double and divide by 100.0
int temp = (int)(longDouble*100.0);
double shortDouble = ((double)temp)/100.0;
public static void main(String[] args) {
double d = 6.3546;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
}
For getting a double back and not a string:
double d = 80.123;
DecimalFormat df = new DecimalFormat("#.##");
double p = Double.parseDouble(df.format(d));
How about:
new java.text.DecimalFormat("0.00").format( yourNumber );
Here is String manipulation to truncate double value up to tow decimal places.
public static String truncateUptoTwoDecimal(double doubleValue) {
String value = String.valueOf(doubleValue);
if (value != null) {
String result = value;
int decimalIndex = result.indexOf(".");
if (decimalIndex != -1) {
String decimalString = result.substring(decimalIndex + 1);
if (decimalString.length() > 2) {
result = value.substring(0, decimalIndex + 3);
} else if (decimalString.length() == 1) {
result = String.format(Locale.ENGLISH, "%.2f",
Double.parseDouble(value));
}
}
return result;
}
return null;
}
As suggested by other you can use class DecimalFormat of java.text.DecimalFormat. We can also use DecimalFormat to round off decimal values.
Example:
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalDemo {
private static DecimalFormat decimalFormatter = new DecimalFormat("#.##");
public static void main(String[] args) {
double number = 2.14159265359;
System.out.println("Original Number : " + number);
System.out.println("Upto 2 decimal : " + decimalFormatter.format(number)); //2.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
decimalFormatter.setRoundingMode(RoundingMode.DOWN);
System.out.println("Down : " + decimalFormatter.format(number)); //2.14
decimalFormatter.setRoundingMode(RoundingMode.UP);
System.out.println("Up : " + decimalFormatter.format(number)); //2.15
}
}
Look into using a Decimal Format :
DecimalFormat twoDForm = new DecimalFormat("#.##");
By using those two methods you can handle all the exceptions also :
private String convertedBalance(String balance){
String convertedBalance = balance.toString();
Double d;
try {`enter code here`
d = Double.parseDouble(balance.toString());
Log.i("ConvertedNumber", "d (amount) = "+d.toString());
d = round(d, 2);
DecimalFormat f = new DecimalFormat("0.00");
convertedBalance = f.format(d);
Log.i("ConvertedNumber", "convertedBalance = "+convertedBalance);
}catch (NumberFormatException e){
Log.i("ConvertedNumber", "Number format exception");
}
return convertedBalance;
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Yes, DecimalFormat: http://www.exampledepot.com/egs/java.text/FormatNum.html
DecimalFormat Class
public static double truncateDecimals(double d, int len) {
long p = pow(10, len);
long l = (long)(d * p);
return (double)l / (double)p;
}
public static long pow(long a, int b) {
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
return result;
}
You can simply use String.format() as below.
double height = 175.8653;
System.out.println("Height is: " + String.format("%.2f", height));
This will trim the double value to two decimal places.

Categories

Resources