String Format double to 00,00 - Java - java

I'm trying to make a double to be this format 00,00
Example
9,21341 > 09,21
10,4312 > 10,43
1,01233 > 01,01
42,543 > 42,54
Currently I'm using the String.Format to round the double
String.format("%s %02.2f - ", example.getName(), example.getDouble());
This does not add the extra zero in front of the double if it is smaller than 10.

Formatter class (which is the basis of String.format method) operates using the concept of "fields". That is, each field is of some specific size and can be padded. In your case, you could use a formating like %05.2f, which would mean a field of size 5, with 2 symbols after the point padded with zeroes to the left.
However, if you need some fine-grained formatting of numbers usually what you are looking for is DecimalFormat class, which allows you to easily customize how the numbers are represented.
Example (ideone link):
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
DecimalFormat decimalFormat = new DecimalFormat("#00.00");
System.out.println(decimalFormat.format(0.99f));
System.out.println(decimalFormat.format(9.99f));
System.out.println(decimalFormat.format(19.99f));
System.out.println(decimalFormat.format(119.99f));
}
}
Output:
00.99
09.99
19.99
119.99

Related

How can I append zeroes in place of empty spaces after the decimal in a number?

This is the question and I am stuck that how can I append zeroes in place of empty spaces after the decimal in java.
enter link description here
Any string formatter can do it.
String s = String.format("%.30f", 1.23);
or
System.out.printf("%.30f %n", 1.23);
Those examples give you 30 places after the decimal point.
A java.text.DecimalFormat instance can do this for you, here is an example:
new DecimalFormat("#,##0.00000").format(1.23); // => 1.23000
new DecimalFormat("#,##0.00000").format(.987643); // => 0.98764
You can use DecimalFormat#format to do so.
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
public static void main(String[] args) {
// Define the formatter
NumberFormat formatter = new DecimalFormat("0.000000");
// Tests
System.out.println(formatter.format(0.3));
System.out.println(formatter.format(123.3));
System.out.println(formatter.format(0.335));
System.out.println(formatter.format(0.0));
System.out.println(formatter.format(1.0));
}
}
Output:
0.300000
123.300000
0.335000
0.000000
1.000000

Converting BigDecimal to double value

I want to ask how to transform all my String to double with exponential.
when I use the string that length is over seven it's doing fine .
new BigDecimal("12345678").doubleValue() => 1.2345678E7
but seven and under I can't export exponential number.
new BigDecimal("1234567").doubleValue() => 1234567.0
what I want is like 1.234567E6.
Is there any way to do this? I've been searching for a while ,but got nothing.
The problem is the type I return must be double . After transforming the value under seven I can only get the value without exponential.
double test = new BigDecimal("1.234567E6").doubleValue() ;//output 1234567.0
but I need it to be 1.234567E6 and return to caller. Is that Impossible?
You should know that 1.2345678e7 and 12345678.0 are exactly the same value, only with different textual representations. You could represent 1234567.0 as 1.234567e6 too. Also exactly the same double, just a different way of writing it out.
The default output shows values with more than a certain number of significant digits in exponential format ("e-form"), otherwise as plain decimal format.
So you may want to change the formatting of the doubles you receive. This can be done with e.g. DecimalFormat or String.format() or similar. That does not change the doubles, only the way they are presented in a string.
For your problem, you want to convert the value to the BigDecimal with exponential, you can use the DecimalFormat. You can also change the scale for the output value digits.
import java.math.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
double a = new BigDecimal("1234567").doubleValue();
String b;
System.out.println(a);
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.DOWN);
formatter.setMinimumFractionDigits(5); //<---Scale
b = formatter.format(a);
System.out.println(b);
}
}
The output will be like:
1234567.0 //Unformatted Value
1.23456E6 //Formatted Value
See the section about Scientific Notation in java.text.DecimalFormat.
For example,
DecimalFormat scientificFormat = new DecimalFormat("0.###E0");
System.out.println(scientificFormat.format(BigDecimal.valueOf(123456L)));
System.out.println(scientificFormat.format(BigDecimal.valueOf(1234567L)));
scientificFormat.setMinimumFractionDigits(10);
System.out.println(scientificFormat.format(BigDecimal.valueOf(12345678L)));
would give you
1,235E5
1,235E6
1,2345678000E7
Change the pattern to match what you're looking for.

Double with exactly two decimal digits in java (without java.text.DecimalFomat)

I have double var and I need to make it in 0.00 format. Works fine with this:
sum = Math.round(sum*100.00)/100.00;
I return it by
return Double.toString(sum);
But instead of for example 2.40 it gives me 2.4 (missing 0 at the end).
I have these imports available:
import static org.junit.Assert.*; import java.util.*;import org.junit.Test;
I solved the problem with DecimalFormat and BigDecimal, but i can't use those libraries.
You can simple format the String
double num = 2.402;
String output = String.format("%.2f", num);
System.out.println(output);
You can use java.lang.String#format() or java.util.Formatter to print the number in a convenient manner.
return String.format("%.2f", sum);
should do the job.
Simply use format
example:
package com.test;
import java.lang.*;
import java.util.*;
public class StringDemo {
public static void main(String[] args) {
double piVal = Math.PI;
/* returns a formatted string using the specified format
string, and arguments */
System.out.format("%f\n", piVal);
}
}
output: 3.141593
The %f allows for the amount of digits you wanna incudes ot %.2f includes 2 digits after.

Java Local Decimal Separator

I tried to get the local decimal separator with the following code:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
//option 1
DecimalFormat format=(DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols=format.getDecimalFormatSymbols();
public char sep=symbols.getDecimalSeparator();
//option 2
double value = 1234.5;
NumberFormat fmt = NumberFormat.getInstance();
String formatted = fmt.format(value);
public String decSep= formatted.substring(5,6);
//option 3
public Locale loc=Locale.getDefault();
DecimalFormatSymbols symbols= new DecimalFormatSymbols(loc);
public char sep=symbols.getDecimalSeparator();
public String decSep=Character.toString(sep);
but I always get "," even if the setting is set to "."
I tried with VB.NET code and it works.
What's wrong or missing in Java code ?
I appreciate your help
Try this :
Locale.setDefault(Locale.US);
This will set every output number with decimal separator. You can also take some input numbers with decimal separator.

Compare first two decimal points

Suppose if I have 3.13 and 4.13, I want to be able to check whether .13 from 3.13 and .13 from 4.13.
I tried many things:
1) converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
2) a = 3.14;
a = a - Math.floor(a); to try to get the decimal alone but i end up getting 0.1400000001
converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work
split uses a regex, so you have to escape the dot.
string.split(".")
should become
string.split("\\.")
With this you should be able to split the string properly and do your comparisons
By the way, i would use Reimenus solution, when you have numbers it's always better to use math if you can. Use strings only if you really need them.
You could separate the fractional part for comparison instead
double value1 = 3.13;
double value2 = 4.13;
double fractional1 = value1 - (long)value1;
double fractional2 = value2 - (long)value2;
System.out.println(Double.compare(fractional1, fractional2));
Read What Every Computer Scientist Should Know About Floating-Point Arithmetic too see
why you're seeing additional digits after your own numerical operation
your second method is actually correct. when comparing double values, you have to include a range.. Java: Double Value Comparison (refer this)
Try this out
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float v1 = 3.13f,v2 = 4.13f;
//Converting float value into String array
String split1[]=Float.toString(v1).split("\\.");
String split2[]=Float.toString(v2).split("\\.");
//Comparing two strings
if(split1[1].equals(split2[1]))
{
System.out.println("Yes");
}
}
}

Categories