How to show user defined digits after a decimal - java

I am trying to figure out how to show the correct number of digits after a decimal, based off a number passed into the method.
public static double chopDecimal(double value, int place)
{
int chopped;
//???
return chopped;
}
So if the value passed is 123.456789 and the place is 2, it should show 123.45.
The print statement is in another method.
System.out.println("***MyMath ChopDecimal Test***");
//Chop Decimal Test 1
if (MyMath.chopDecimal(123.456789, 2) == 123.45)
{
System.out.println("Chop Decimal Test 1 Passed");
}
else
{
System.out.printf("Chop Decimal Test 1 Failed. Your answer: %f Correct Answer: 123.45\n",
MyMath.chopDecimal(123.456789, 2));
}
//Chop Decimal Test 2
if (MyMath.chopDecimal(.98765, 4) == .9876)
{
System.out.println("Chop Decimal Test 2 Passed");
}
else
{
System.out.printf("Chop Decimal Test 2 Failed. Your answer: %f Correct Answer: .9876\n",
MyMath.chopDecimal(.98765, 4));
}

This is possible using java.text.NumberFormat, although when you wish to convert to String for 'showing' purposes.
To match your example though, I've converted it babck to a double:
public static double chopDecimal(double value, int place)
{
String chopped = NumberFormat.getInstance().setMaximumFractionDigits( place ).format( value );
return Double.valueOf( chopped );
}

I suggest you to use the java Rounding Mode.
Simple example:
public static void main(String[] args) {
System.out.println(chopDecimal(123.456789, 2));
}
public static String chopDecimal(double value, int place)
{
// Parameter is the pattern
DecimalFormat format = new DecimalFormat("0.00");
format.setRoundingMode(RoundingMode.HALF_UP);
return format.format(value);
}
This question is duplicated:
How to round a number to n decimal places in Java
Reference:
Oracle Documentation

All of the answers above are pretty great, but if this for something you need to be able to explain, I wrote the segment of code below with all pretty basic tools of programming. Study this process below, it's not always about the solution, more so about can you come up with a solution. Always keep that in mind when solving any problem. There is always time later to improve your solution.
public static void main(String[] args) {
chopDecimal(123.456789,2);
}
public static double chopDecimal(double value, int place)
{
String valToStr = Double.toString(value);
int decimal=0;
for(int i = 0; i < valToStr.length(); i++)
{
if(valToStr.charAt(i) == '.')
{
decimal = valToStr.indexOf(valToStr.charAt(i));
System.out.println(decimal);
break;
}
}
String newNum = valToStr.substring(0,(++decimal+place));
System.out.println(newNum);
double chopped = Double.parseDouble(newNum);
return chopped;
}
}
Let me know if you have any questions.

You can use BigDecimal and setScale:
double chopped = BigDecimal
.valueOf(value)
.setScale(place, RoundingMode.DOWN)
.doubleValue()

Related

Round percentage value to nearest number

I wanted to convert a number which is in string format to a percentage value with one decimal point. Below is my sample input and expected output.
Expected results:
"0.0195" => "2.0%"
"0.0401" => "4.0%"
I know this may be a simple question but I am not able to find the exact solution for this using java APIs, I tried all the rounding modes present under RoundingMode enum, but no rounding mode gives my expected result. Could you please help, I may be missing something.
import java.math.RoundingMode;
import java.text.NumberFormat;
public class RoundingModeExample {
public static void main(String[] args) {
System.out.println(formatPercentage("0.0195") + "(expected 2.0%)");
System.out.println(formatPercentage("0.0401") + "(expected 4.0%)");
}
private static String formatPercentage(String number) {
String formattedValue = "";
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(1);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
try {
formattedValue = numberFormat.format(Double.valueOf(number));
} catch (NumberFormatException e) {
formattedValue = number;
}
return formattedValue;
}
}
Output of the above program:
1.9%(expected 2.0%)
4.0%(expected 4.0%)
The problem with 0.0195 is that there is no double precision number that is exactly mathematically equal to it. When you write 0.0195 in program source code or parse the string "0.0195" into double, the number you get is actually a little bit less. That's why the formatter rounds it to 1.9%.
You can get around this by not using the double data type at all:
formattedValue = numberFormat.format(new BigDecimal(number));

How to determine which rounding method is used internally by BigDecimal.round() in java

I am using BigDecimal to round an input based on desired significant figures, actual input and desired significant figures comes from a JtextPane. This is the sample code;
String input = "1234.56";
String sf = "3";
String ans;
BigDecimal decRep = new BigDecimal(Double.parseDouble(input));
decRep = decRep.round(new MathContext(Integer.parseInt(sf)));
ans = String.valueOf(decRep.doubleValue());
System.out.println(ans);
This will result to 1230.0 which is well and fine. But it also required to output if it rounded down or if it rounded up.
Is there a way to determine so?
If I understand your question correctly, you want to find out whether a value was rounded up or down in respect to its original value. This would be the easiest way to do that:
public BigDecimal roundAndLog(String input, String sigFigs) {
BigDecimal decimal = new BigDecimal(input);
BigDecimal decimalRounded = decimal.round(new MathContext(Integer.parseInt(sigFigs)));
int compared = decimalRounded.compareTo(decimal);
if (compared == -1) {
System.out.println("Rounded down!");
} else if (compared == 0) {
System.out.println("Value didn't change!");
} else {
System.out.println("Rounded up!");
}
return decimalRounded;
}

Only return a decimal if it's not a whole number. JAVA

I've been trying to write a function isWhole that is given a double and looks to see if it's a whole number if it is return the value without the decimal(as an int?) else return it with 3 decimal places(I can do this part with number format.
My question is how can I check if a double is a whole number and even a recursive decimal?
[UPDATE] returns value - with 3 decimal places
public boolean isWhole(double value) {
return Math.floor(value) == value;
}
You can't have a function that returns either int or double
To convert double to int; simply typecast :- int valueInt = (int) valueDouble;
My first advice would be: keep it simple. Java has functions that make this sort of thing easy:
import java.Math;
public class MyFunctionsLibrary {
public static boolean isWhole(double x) {
if(x - Math.floor(x) == 0)
return true;
else
return false;
}
public static void testIt() {
double a = 123.456;
Integer whole = null;
Double nonWhole = null;
if(isWhole(a))
whole = new Integer(Math.floor(a));
else
nonWhole = new Double(a);
}
}
if(Math.abs(in-Math.floor(in)) < 0.001){
/* is whole number */
} else {
/* is not whole number */
}
Whole number isn't really defined for doubles, so a whole number can be seen as a number that has would not result in n.000. 0.001 is chosen specifically because it is the intended output precision.
This was my original answer:
How about
Math.floor(x)==x
The floor leaves the x unchanged, bit-by-bit if it is a mathematical integer (say the docs), so the equality should hold exactly when there is nothing to round.
After some thought, I think using exact comparison may lead to unwanted results. The question is, what the requirements of the OP really are. Is it
If it is a mathematical integer, show the number with no digits
after the decimal point, if it is not, show 3 digits after the
decimal point. Or is it
If formatting with three digits results in 000 after the decimal point, show only an integer.
The solution shown above and in other answers only works, if (1) is the requirement, because the number 2.000001 would turn out as 2.000, because it is not a mathematical integer.
If the Locale is fixed to a default, formatting 1.0 for the endsWith()-pattern can of course be optimized into a fixed string like ".000" or ",000".
If (2) is actually requested, my hunch is that there is no way around first formatting the number to a string and only then stripping the zeros, like so:
String format(Locale l, double d) {
String zeros = String.format(l, "%.3f", 1.0d);
String s = String.format(l, "%.3f", d);
if (s.endsWith(zeros.substring(1))) {
return s.substring(0, s.length()-4);
}
return s;
}
To see if a double is a whole number use
double d;
int whole = (int) d;
if(whole == d){
return whole;
}
else{
(your formatting here)
return formattedDouble;
}
You could check if it is recursive by creating:
String s = d + "";
for(int i = 1; i < s.length(); i++){
if(s.charAt(i) == s.charAt(i-1)){
continue;
}
else{
return false;
}
}

How can I always print 15 non-zero digits in Java?

Say for example that I have the Double value 1.23456789123456. I want to be able to multiply this number by various powers of 10 and display the output as
123.456789123456
12345.6789123456
0.0123456789123456
0.000123456789123456
etc
Is there any way to do this in Java without having to use if...then statements to handle the changing decimal precision required for different powers of 10?
This could be improved, but it's close:
public class Test {
public static void main(final String[] args) {
System.out.println(format(123.456789123456d));
System.out.println(format(12345.6789123456d));
System.out.println(format(0.0123456789123456d));
System.out.println(format(0.000123456789123456d));
}
public static String format(final double d) {
final int before = 16 - Integer.toString((int) d).length();
final String format = "%" + (16 + before) + "." + before + "f";
return String.format(format, d);
}
Output:
123.4567891234560
12345.67891234560
0.012345678912346
0.000123456789123
If you don't need the number as an actual floating point value, try representing the number as a String without a decimal point (e.g., "123456789123456"). Then using the String.substring() method, you can print the decimal point wherever you want, include leading zeroes, etc. I don't know that you can totally avoid using any if statements, but the logic should be fairly straightforward.
For instance, this prints the decimal after three significant digits:
String n = "123456789123456";
System.out.print(n.substring(0, 3));
System.out.print('.');
System.out.print(n.substring(3));
Check out the DecimalFormat class

convert hexadecimal number string to double-precision number in java

how can we convert hexadecimal number string to double-precision number in java ?
in matlab it's simple :
>> hex2num('c0399999a0000000')
ans =
-25.6000
but could I do the same things in java also ?
I tried parseInt() but this number is not integer.
I think you want Double.longBitsToDouble, like this:
public class Test {
public static void main(String[] args) {
String hex = "c0399999a0000000";
long longHex = parseUnsignedHex(hex);
double d = Double.longBitsToDouble(longHex);
System.out.println(d);
}
public static long parseUnsignedHex(String text) {
if (text.length() == 16) {
return (parseUnsignedHex(text.substring(0, 1)) << 60)
| parseUnsignedHex(text.substring(1));
}
return Long.parseLong(text, 16);
}
}
(The fact that long is signed in Java makes this more awkward than you'd really want, but hey...)
First make a long, and then call longBitsToDouble

Categories