This is a very trivial problem for you guys. Please suggest me the way to achieve the optimal solution. My requirement is, I have an incoming Double value, so if the value after the decimal point is 0, than truncate everything after the decimal. For example: 30.0 should become 30, where as 30.12 or 30.1 should stay as it is. Till now I have only figured out a way to know how many digits are there after the decimal point.
package com.convertdatatypes;
public class DoubleCheck {
public static void main(String args[]){
Double value = 30.153;
String val = value.toString();
String[] result = new String[2];
for(int i=0; i<val.length(); i++){
result = val.split("\\.");
System.out.println("Number of Decimals in: " + val + " : " + result[1].length());
}
}
}
use java's DecimalFormat with the following pattern:
0.##
See http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
Another approach is to use the following
double value = 30.153;
Object value2 = value == (long) value ? String.valueOf((long) value) : value;
System.out.println("Number of Decimals in: " + value2);
This way it prints as a long if the value is unchanged or a double otherwise.
Related
I am invoking a method called "calculateStampDuty", which will return the
amount of stamp duty to be paid on a property. The percentage calculation works
fine, and returns the correct value of "15000.0". However, I want to display the value to
the front end user as just "15000", so just want to remove the decimal and any preceding values
thereafter. How can this be done? My code is below:
float HouseValue = 150000;
double percentageValue;
percentageValue = calculateStampDuty(10, HouseValue);
private double calculateStampDuty(int PercentageIn, double HouseValueIn){
double test = PercentageIn * HouseValueIn / 100;
return test;
}
I have tried the following:
Creating a new string which will convert the double value to a string, as per below:
String newValue = percentageValue.toString();
I have tried using the 'valueOf' method on the String object, as per below:
String total2 = String.valueOf(percentageValue);
However, I just cannot get a value with no decimal places. Does anyone know
in this example how you would get "15000" instead of "15000.0"?
Thanks
Nice and simple. Add this snippet in whatever you're outputting to:
String.format("%.0f", percentageValue)
You can convert the double value into a int value.
int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).
I did this to remove the decimal places from the double value
new DecimalFormat("#").format(100.0);
The output of the above is
100
You could use
String newValue = Integer.toString((int)percentageValue);
Or
String newValue = Double.toString(Math.floor(percentageValue));
You can convert double,float variables to integer in a single line of code using explicit type casting.
float x = 3.05
int y = (int) x;
System.out.println(y);
The output will be 3
I would try this:
String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.
int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
Try this you will get a string from the format method.
DecimalFormat df = new DecimalFormat("##0");
df.format((Math.round(doubleValue * 100.0) / 100.0));
Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
Use
Math.Round(double);
I have used it myself. It actually rounds off the decimal places.
d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20
d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19
Hope it Helps :-)
the simple way to remove
new java.text.DecimalFormat("#").format(value)
The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.
DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);
String year = decimalFormat.format(32024.2345D);
With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.
String newValue = ((int) percentageValue).toString();
You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal
String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose
The problem is two fold-
To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.
Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.
So use the following with the above known risk.
double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
Alternatively, you can use the method int integerValue = (int)Math.round(double a);
Double i = Double.parseDouble("String with double value");
Log.i(tag, "display double " + i);
try {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0); // set as you need
String myStringmax = nf.format(i);
String result = myStringmax.replaceAll("[-+.^:,]", "");
Double i = Double.parseDouble(result);
int max = Integer.parseInt(result);
} catch (Exception e) {
System.out.println("ex=" + e);
}
declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Double value = double value ;
Long longValue = value.longValue();
String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
public class RemoveDecimalPoint{
public static void main(String []args){
System.out.println(""+ removePoint(250022005.60));
}
public static String removePoint(double number) {
long x = (long) number;
return x+"";
}
}
This should do the trick.
System.out.println(percentageValue.split("\\.")[0]);
Try:
String newValue = String.format("%d", (int)d);
I am still a bit new to programming and very new to Java, the kind of code I want is something like this:
double a = 10;
double b = 1234.123;
double c = 123.1234;
System.out.println(a);
System.out.println(b);
System.out.println(c);
And I want the output to read like:
10
1234.12
123.123
So basically, I want the numbers to be truncated to fit the number of spaces specified. In the above example, I wanted the numbers to fit into a field of 7 digits. I tried using printf() and NumberFormat, but neither of these seemed to work quite right, what other options do I have?.
Thanks for responding.
EDIT: #Pete, here is what I have been trying.
public static void main(String[] args) {
double num1 = 123.456789;
double num2 = 12.3456789;
double num3 = 1.23456789;
// create number format object
NumberFormat nf = NumberFormat.getInstance();
// limits number of fraction digits to five
nf.setMinimumFractionDigits(5);
System.out.println("Using NumberFormat:");
System.out.println();
System.out.println("num1 = " + nf.format(num1));
System.out.println("num2 = " + nf.format(num2));
System.out.println("num3 = " + nf.format(num3));
System.out.println("-------------------------------");
System.out.println("Using printf:");
System.out.println();
System.out.printf("%7f\n", num1);
System.out.printf("%7f\n", num2);
System.out.printf("%7f\n", num3);
}
The output for the above code is:
Using NumberFormat:
num1 = 123.45679
num2 = 12.34568
num3 = 1.23457
-------------------------------
Using printf:
123.456789
12.345679
1.234568
I am looking for a way to format any number to fit a field with a width of 7, and once the number of spaces is exceeded, it will begin to truncate from the end. I want a technique that will work regardless of which number is entered. both printf() and NumberFormat produce a specified number of decimal places, but neither cause my output to be truncated.
You can use DecimalFormat for the purpose. Define a DecimalFormat object in your class
private static DecimalFormat df2 = new DecimalFormat(".##");
While printing the values say stored in a variable called result, use below code to print the formatted value:
System.out.println(df2.format(result));
When i execute the below code:
public class Test {
public static void main(String args[]){
DecimalFormat format = new DecimalFormat();
Double value = new Double(-1350825904190559999913623552.00);
StringBuffer buffer = new StringBuffer();
FieldPosition position = new FieldPosition(0);
format.format(new BigDecimal(value), buffer, position);
System.out.println(buffer);
}
}
This correctly prints -1,350,825,904,190,559,999,913,623,552.
I have code which does go through a lot of doubles so I dont want the conversion from double to bigdecimal. I figured the processing time for BigDecimal is large.
So i do format.format(value, buffer, position)
And i see the precision is lost.
The output I get is -1,350,825,904,190,560,000,000,000,000.
What am i doing wrong here? Is there a better way to deal with this and still retain the precision. I don't want to deal with BigDecimals here but just work with the decimals.
Any suggestions?
double doesn't have infinite precision, and you can't gain more precision than a double has by converting a double to a BigDecimal (like you can't gain more precision with an int when you do double r = 1/3; which is 0.0 because it widens an int to a double). Instead, you could use a String. Something like
DecimalFormat format = new DecimalFormat();
String value = "-1350825904190559999913623552.00";
System.out.println(format.format(new BigDecimal(value)));
It isn't lost during formatting. It is lost right here:
Double value = new Double(-1350825904190559999913623552.00);
A double only has about 15.9 significant decimal digits. It doesn't fit. There was a precision loss at compile time when the floating-point literal was converted.
The issue is in the output formatting, specifically how doubles are converted to strings by default. Each double number has an exact value, but it is also the result of string to double conversion for a range of decimal fractions. In this case, the exact value of the double is -1350825904190559999913623552, but the range is [-1350825904190560137352577024,-1350825904190559862474670080].
The Double toString conversion picks the number from that range with the fewest significant digits, -1.35082590419056E27. That string does convert back to the original value.
If you really want to see the exact value, not just enough digits to uniquely identify the double, your current BigDecimal approach works well.
Here is the program I used to calculate the numbers in this answer:
import java.math.BigDecimal;
public class Test {
public static void main(String args[]) {
double value = -1350825904190559999913623552.00;
/* Get an exact printout of the double by conversion to BigDecimal
* followed by BigDecimal output. Both those operations are exact.
*/
BigDecimal bdValue = new BigDecimal(value);
System.out.println("Exact value: " + bdValue);
/* Determine whether the range is open or closed. The half way
* points round to even, so they are included in the range for a number
* with an even significand, but not for one with an odd significand.
*/
boolean isEven = (Double.doubleToLongBits(value) & 1) == 0;
/* Find the lower bound of the range, by taking the mean, in
* BigDecimal arithmetic for exactness, of the value and the next
* exactly representable value in the negative infinity direction.
*/
BigDecimal nextDown = new BigDecimal(Math.nextAfter(value,
Double.NEGATIVE_INFINITY));
BigDecimal lowerBound = bdValue.add(nextDown).divide(BigDecimal.valueOf(2));
/* Similarly, find the upper bound of the range by going in the
* positive infinity direction.
*/
BigDecimal nextUp = new BigDecimal(Math.nextAfter(value,
Double.POSITIVE_INFINITY));
BigDecimal upperBound = bdValue.add(nextUp).divide(BigDecimal.valueOf(2));
/* Output the range, with [] if closed, () if open.*/
System.out.println("Range: " + (isEven ? "[" : "(") + lowerBound + ","
+ upperBound + (isEven ? "]" : ")"));
/* Output the result of applying Double's toString to the value.*/
String valueString = Double.toString(value);
System.out.println("toString result: " + valueString);
/* And use BigDecimal as above to print the exact value of the result
* of converting the toString result back again.
*/
System.out.println("exact value of toString result as double: "
+ new BigDecimal(Double.parseDouble(valueString)));
}
}
Output:
Exact value: -1350825904190559999913623552
Range: [-1350825904190560137352577024,-1350825904190559862474670080]
toString result: -1.35082590419056E27
exact value of toString result as double: -1350825904190559999913623552
You cannot represent 1350825904190559999913623552.00 accurately with a Double. If you would like to know why, explore this article.
Should you want to represent the value, I would advise using the code you have used in your question: new BigDecimal( value ), where value is actually a String representation.
I'm making a program that turns a large number into a string, and then adds the characters of that string up. It works fine, my only problem is that instead of having it as a normal number, Java converts my number into standard form, which makes it hard to parse the string. Are there any solutions to this?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);
Other answers are correct, you could use a java.text.NumberFormat (JavaDoc) to format your output. Using printfis also an option for formatting, similar to NumberFormat. But I see something else here. It looks like you mixed up your data types: In
nq = (long) Math.pow(2l, 1000l);
you are already truncating the double return value from Math to a long. Then you should use long as data type instead of double for the conversion. So use Long.toString(long), this will not add any exponent output.
Use Long.toString(nq) instead of Double.toString(nq); in your code.
As you say: "NumberFormat". The class.
BigInteger is easy to use and you don't risk precision problems with it. (In this particular instance I don't think there is a precision problem, because Math.pow(2, 1001) % 100000 returns the correct last 5 digits, but for bigger numbers eventually you will lose information.) Here's how you can use BigInteger:
groovy:000> b = new BigInteger(2L)
===> 2
groovy:000> b = b.pow(1001)
===> 214301721437253464189685009812000362112280962341106721488750077674070210224
98722449863967576313917162551893458351062936503742905713846280871969155149397149
60786913554964846197084214921012474228375590836430609294996716388253479753511833
1087892154125829142392955373084335320859663305248773674411336138752
groovy:000> ((b + "").toList().collect {new Integer(it)}).inject(0) {sum, n -> sum + n}
===> 1319
Here's the same thing in Java:
public class Example
{
public static void main(String[] args)
{
int sum = 0;
for (char ch : new java.math.BigInteger("2").pow(1001).toString().toCharArray()) {
sum += Character.digit(ch, 10);
}
System.out.println(sum);
}
}
Link to the javadoc for NumberFormat: Javadoc
just replace last line:
System.out.println(result);
with
System.out.printf("%d", result);
I'm doing my first attempts to use BigDecimal. It seems tricky.i am running into an issue and i would like to understand what is causing it.
public static String nominator(String nbrPeople)
{
BigDecimal nom = new BigDecimal("365") ;
BigDecimal days = new BigDecimal("365") ;
int limit = Integer.parseInt(nbrPeople);
for (int i = 0 ; i < limit ; i++ )
{
days = days.substract(i) ;
nom = nom.multiply(days) ;
}
return nbrPeople ;
}
this is part of a larger program. it is a method that should compute something like this:
365 x (365-1) x (365-2) x (365-3) etc depending on the value of nbrPeople passed in.
i would like to understand why i get the following error message:
cannot find symbol
method substract(int)
not looking for a discussion on factorials but rather on the use of BigDecimal (or BigInteger). I'm using BigDecimal because at a later stage i will need to divide, resulting in floating point.
EDIT
EDIT 2
first edit removed (code) to make the post more readable- the correct code has been posted below by a kind programmer
Because the method is named subtract not substract.
And the parameter has to be BigInteger too:
http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html#subtract(java.math.BigInteger)
You are attempting to subtract an int from a BigDecimal. Since there is no method subtract(int x) on the BigDecimal class, you get the cannot find symbol compiler error.
This should work:
public static String nominator(String nbrPeople)
{
BigDecimal nom = new BigDecimal("365") ;
BigDecimal days = new BigDecimal("365") ;
int limit = Integer.parseInt(nbrPeople);
for (int i = 0 ; i < limit ; i++ )
{
days = days.subtract(new BigDecimal(i)) ;
nom = nom.multiply(days) ;
}
return nbrPeople ;
}
as there is no BigDecimal.subtract(int) method, only a BigDecimal.subtract(BigDecimal) method.
Typo - you misspelled "subtract".
Should be subtract ( with a single s )
Whenever you see cannot find symbol message, you are trying to use a method that doesn't exist or a variable that doesn't exists. Most of the time ( as in this case ) due to a misspelling or because you didn't import the class.
BigDecimal can only subtract another BigDecimal. you are subtracting an int. See
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal)
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal
import java.math.BigDecimal;
import java.util.Scanner;
public class BigDecimal_SumExample {
public static void main(String args[]) {
BigDecimal number1;
BigDecimal number2;
BigDecimal sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of number 1");
number1 = sc.nextBigDecimal();
System.out.println("Enter the value of number 2");
number2 = sc.nextBigDecimal();
BigDecimal a = new BigDecimal(""+number1);
BigDecimal b = new BigDecimal(""+number2);
BigDecimal result = a.add(b);
System.out.println("Sum is Two numbers : -> ");
System.out.println(result);
}
}
**Output is**
Enter the value of number 1
68237161328632187132612387312687321678312612387.31276781237812
Enter the value of number 2
31232178631276123786321712369812369823162319862.32789129819299
Sum is Two Big Decimal numbers : ->
99469339959908310918934099682499691501474932249.64065911057111