How to use decimal number without creating a String resource - java

In Java and Kotlin there is an API that can used to show a time without having to create a string resource.
In the example line of code below, this value allows the time of 8 hours after midnight to automatically chnage the way its displayed depending on the device locale.
val timeCustom = LocalTime.of(8, 0)
Is there something similar that can be used for a decimal number, where the value automatically uses a specific demical symbol dpending on the locale? (. or ,).
For example, to describe the height of something (e.g. 5 point 2 metres):
val decimalNumber = Decimal.of(5,2)
Is there something like this available?

You can use Locale.getDefault() e.g.
import java.text.NumberFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale currentLocale = Locale.getDefault();
Integer quantity = 123456;
Double amount = 345987.246;
NumberFormat numberFormatter;
String quantityOut;
String amountOut;
numberFormatter = NumberFormat.getNumberInstance(currentLocale);
quantityOut = numberFormatter.format(quantity);
amountOut = numberFormatter.format(amount);
System.out.println(quantityOut);
System.out.println(amountOut);
}
}
Output:
123,456
345,987.246

Related

How can i format turkish lira with symbol?

I tried to do it with the locale, but it only appears as text and the symbol doesn't come out. I am using JAVA 14 SDK.
Code I tried:
Locale tr = new Locale("tr", "TR");
BigDecimal points = new BigDecimal(175678.64);
System.out.println(NumberFormat.getCurrencyInstance(tr).format(points));
Output:
175.678,64 TL
I want:
₺175.678,64
No problem
I broke out your code to multiple lines for easier debugging.
When I run it in the IdeOne.com site, I get your desired output.
By the way, you should pass your input number as text (add quote marks). Otherwise you are defeating the purpose of using BigDecimal.
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.* ;
import java.text.* ;
/* 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
{
// your code goes here
Locale locale = new Locale("tr", "TR");
BigDecimal points = new BigDecimal( "175678.64" ) ;
NumberFormat f = NumberFormat.getCurrencyInstance( locale ) ;
String output = f.format( points ) ;
System.out.println( output ) ;
}
}
When run:
₺175.678,64
Consider using the Currency class of java.util.Currency.
The Currency class has two methods getSymbol() and getSymbol(Locale locale). In your case you should use the second method with the locale parameter. This will return a String that represents the currency symbol for turkish lira.
You can initialize your Currency object like this:
Currency currency = Currency.getInstance(tr);
and
currency.getSymbol(tr);
will return the currency symbol as a String
In addition, you should know that the unidoce representation of turkish lira symbol as a char in Java is \u20BA
try this change 'Locale.CANADA' with your country
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.CANADA);
String currency = format.format(number);
System.out.println("Currency in Canada : " + currency);

NumberFormat vs Joda money

I need to display currency amount with the symbol and format based on currency code. Currently, I'm using a default locale for each currency code since I don't have access to the exact locale along with the currency code and using NumberFormat.format() to get the formatted currency amount with format and symbol. Does Joda money do this all - provide currency code and it displays the formatted currency with symbol? Any help/direction regarding this is appreciated.
I just found out about joda-money, I'm testing it to see if it fits in my project requirements. I read your question and decided to answer it while testing the library.
For what I could see inside the joda-money jar it has very few classes and provide the basic currency management and a formatter.
It seems that at the early stage in which joda-money is the formatter still needs the Locale to print the money symbol, as you can see in my code. (The code is in scala but the methods call are the same in Java)
import org.joda.money.format.MoneyFormatterBuilder
import org.joda.money.{Money, CurrencyUnit}
def formatterBuilder() = new MoneyFormatterBuilder().appendCurrencySymbolLocalized().appendAmount()
def moneyFormatter(locale: java.util.Locale) = formatterBuilder().toFormatter(locale)
def moneyFormatter() = formatterBuilder().toFormatter
val usd: CurrencyUnit = CurrencyUnit.of("USD")
val money = Money.of(usd, 23232312d) // or just Money.parse("USD 23232312")
moneyFormatter().print(money) // res0: String = USD23,232,312.00
moneyFormatter(java.util.Locale.US).print(money) // res1: String = $23,232,312.00
As you can see, the Locale is needed to print the '$' symbol.
Additionally I tried with another currency, the yen (Japan currency). I printed it with the US locale and the result was something I didn't spec.
val japan = Money.parse("JPY 23232312")
moneyFormatter().print(japan) // res2: String = JPY23,232,312
moneyFormatter(java.util.Locale.JAPAN).print(japan) // res3: String = ¥23,232,312
moneyFormatter(java.util.Locale.US).print(japan) // res4: String = JPY23,232,312
EDIT:
You could also create an abstract class as a wrapper for Money, like this:
abstract class Currency(amount: BigDecimal, locale: java.util.Locale) {
val currencyUnit: CurrencyUnit = CurrencyUnit.getInstance(locale)
val money: Money = Money.of(currencyUnit, amount)
def formatted: String = new MoneyFormatterBuilder().appendCurrencySymbolLocalized().appendAmount().toFormatter(locale).print(money)
// implement others Money methods
}
class USDollars(amount: BigDecimal) extends Currency(amount, java.util.Locale.US)
public static void main(String[] args) throws Exception {
Currency usd = java.util.Currency.getInstance("USD");
NumberFormat format = java.text.NumberFormat.getCurrencyInstance(java.util.Locale.US);
format.setCurrency(usd);
System.out.println(format.format(23232312));
}
Output
$23,232,312.00

Java: altering locale formatting

I would like to modify the way my application locale formats and displays numbers.
In my case the locale is "it_IT", so numbers are formatted with '.' as GroupingSeparator and ',' as DecimalSeparator. Is it possible to alter or remove those symbols at global application level?
Depending on what do you want there a different ways. See some below...
1 set the default locale in your applicationLocale.setDefault(Locale.UK); this will use a comma as GroupingSeparator and a point as DecimalSeparator
2 you can create the java.text.NumberFormat for a specific locale NumberFormat.getInstance(Locale.UK), will behave like solution 1)
3 you can use one of the above an remove the GroupingSeparator
NumberFormat formatUK = NumberFormat.getInstance(Locale.UK);
formatUK.setGroupingUsed(false);
edit:
import java.text.NumberFormat;
import java.util.Locale;
public class Foo {
public static void main(String[] args) {
NumberFormat formatUK = NumberFormat.getInstance(Locale.UK);
double someValue = 1234567.8899;
System.out.printf("%16s: %15s%n", "with grouping", formatUK.format(someValue));
formatUK.setGroupingUsed(false);
System.out.printf("%16s: %15s%n", "without grouping", formatUK.format(someValue));
}
}

Is it normal that is not rounding while parsing? NumberFormat

Why does it not round in the parsing process?
NumberFormat format = NumberFormat.getInstance();
System.out.println(format.getMaximumFractionDigits());// 3
System.out.println(format.getRoundingMode());// half even
Double dob = (Double)format.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
The digit counts are only used for formatting. When you parse a number you always get the number that best matches the input, even if it has more digits than the NumberFormat would use to format.
To parse a number from a string and then round to a given number of fractional digits you can use BigDecimal from the java.math package:
BigDecimal bd = BigDecimal("1212.35656");
double dob = bd.setScale(3, RoundingMode.HALF_EVEN).doubleValue();
To obtain what you desire you need to call the formatter metod of the implementation NumberFormat loaded (in your case DecimalFromat); i just added the needed lines at the end and wrapped in a main:
import java.text.NumberFormat;
public class NumberFormatRounding {
public static void main(String[] args) throws Exception{
NumberFormat formatter = NumberFormat.getInstance();
System.out.println(formatter.getMaximumFractionDigits());// 3
System.out.println(formatter.getRoundingMode());// half even
Double dob = (Double) formatter.parse("1212.35656");
System.out.println(dob);// output is 1212.35656
String formattedDob = formatter.format(dob.doubleValue());
System.out.println(formattedDob);// output is 1212.357
}
}
Note that the formattedDob is a String

Convert Double to String value preserving every digit

How do I convert a double value with 10 digits for e.g 9.01236789E9 into a string 9012367890 without terminating any of its digits ?
I tried 9.01236789E9 * Math.pow(10,9) but the result is still double "9.01236789E18"
double d = 9.01236789E9;
System.out.println(BigDecimal.valueOf(d).toPlainString());
While 10 digits should be preservable with no problems, if you're interested in the actual digits used, you should probably be using BigDecimal instead.
If you really want to format a double without using scientific notation, you should be able to just use NumberFormat to do that or (as of Java 6) the simple string formatting APIs:
import java.text.*;
public class Test
{
public static void main(String[] args)
{
double value = 9.01236789E9;
String text = String.format("%.0f", value);
System.out.println(text); // 9012367890
NumberFormat format = NumberFormat.getNumberInstance();
format.setMaximumFractionDigits(0);
format.setGroupingUsed(false);
System.out.println(format.format(value)); // 9012367890
}
}
Try String.format("%20.0f", 9.01236789E9)
Note though it's never an exact value, so "preserving every digit" doesn't really make sense.
You can use it.
String doubleString = Double.toString(inValue)
inValue -----> Described by you.to what position you want to Change double to a string.
In this case, you can also do
double value = 9.01236789E9;
System.out.println((long) value); // prints 9012367890

Categories