Double and decimal java

Double and decimal java

  • The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
  • How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
  • GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
  • 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
  • The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
  • API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .
Читайте также:  Php check if url have http

Источник

Number Formatting in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn about the different approaches to number formatting in Java, and how to implement them.

2. Basic Number Formatting With String#format

The String#format method is very useful for formatting numbers. The method takes two arguments. The first argument describes the pattern of how many decimals places we want to see, and the second argument is the given value:

double value = 4.2352989244d; assertThat(String.format("%.2f", value)).isEqualTo("4.24"); assertThat(String.format("%.3f", value)).isEqualTo("4.235");

3. Decimal Formatting by Rounding

In Java, we have two primitive types that represent decimal numbers, float and decimal:

double myDouble = 7.8723d; float myFloat = 7.8723f;

The number of decimal places can be different depending on the operations being performed. In most cases, we’re only interested in the first couple of decimal places. Let’s take a look at some ways to format a decimal by rounding.

3.1. Using BigDecimal for Number Formatting

The BigDecimal class provides methods to round to a specified number of decimal places. Let’s create a helper method that will return a double, rounded to a desired number of places:

public static double withBigDecimal(double value, int places)

We’ll start with a new instance of BigDecimal with our original decimal value. Then, by setting the scale, we’ll provide the number of decimal places we want, and how we want to round our number. Using this method allows us to easily format a double value:

double D = 4.2352989244d; assertThat(withBigDecimal(D, 2)).isEqualTo(4.24); assertThat(withBigDecimal(D, 3)).isEqualTo(4.235);

3.2. Using Math#round

We can also take advantage of the static methods in the Math class to round a double value to a specified decimal place. In this case, we can adjust the number of decimal places by multiplying and later dividing by 10^n. Let’s check our helper method:

public static double withMathRound(double value, int places) < double scale = Math.pow(10, places); return Math.round(value * scale) / scale; >
assertThat(withMathRound(D, 2)).isEqualTo(4.24); assertThat(withMathRound(D, 3)).isEqualTo(4.235);

However, this option is only recommended in particular cases, as sometimes the output might be rounded differently than expected before it’s printed.

This is because Math#round is truncating the value. Let’s see how this can happen:

System.out.println(withMathRound(1000.0d, 17)); // Gives: 92.23372036854776 !! System.out.println(withMathRound(260.775d, 2)); // Gives: 260.77 instead of expected 260.78 

So please note that this method is only listed for learning purposes.

4. Formatting Different Types of Numbers

In some particular cases, we may want to format a number for a specific type, like currency, large integer, or percentage.

4.1. Formatting Large Integers With Commas

Whenever we have a large integer in our application, we may want to display it with commas by using DecimalFormat with a predefined pattern:

public static String withLargeIntegers(double value) < DecimalFormat df = new DecimalFormat("###,###,###"); return df.format(value); >int value = 123456789; assertThat(withLargeIntegers(value)).isEqualTo("123,456,789");

4.2. Padding a Number

In some cases, we may want to pad a number with zeros for a specified length. Here, we can use the String#format method, as described earlier:

public static String byPaddingZeros(int value, int paddingLength) < return String.format("%0" + paddingLength + "d", value); >int value = 1; assertThat(byPaddingOutZeros(value, 3)).isEqualTo("001");

4.3. Formatting Numbers With Two Zeros After the Decimal

To be able to print any given number with two zeros after the decimal point, we’ll again use the DecimalFormat class with a predefined pattern:

public static double withTwoDecimalPlaces(double value) < DecimalFormat df = new DecimalFormat("#.00"); return new Double(df.format(value)); >int value = 12; assertThat(withTwoDecimalPlaces(value)).isEqualTo(12.00);

In this case, we created a new format with a pattern specifying two zeros after the decimal point.

4.4. Formatting and Percentages

From time to time we might need to display percentages.

In this case, we can use the NumberFormat#getPercentInstance method. This method allows us to provide a Locale to print the value in a format that’s correct for the country we specified:

public static String forPercentages(double value, Locale locale) < NumberFormat nf = NumberFormat.getPercentInstance(locale); return nf.format(value); >double value = 25f / 100f; assertThat(forPercentages(value, new Locale("en", "US"))).isEqualTo("25%");

4.5. Currency Number Formatting

A common way to store currencies in our application is by using the BigDecimal. If we want to display them to the user, we can use the NumberFormat class:

public static String currencyWithChosenLocalisation(double value, Locale locale)

We get the currency instance for a given Locale and then simply call the format method with the value. The result is the number displayed as a currency for the specified country:

double value = 23_500; assertThat(currencyWithChosenLocalisation(value, new Locale("en", "US"))).isEqualTo("$23,500.00"); assertThat(currencyWithChosenLocalisation(value, new Locale("zh", "CN"))).isEqualTo("¥23,500.00"); assertThat(currencyWithChosenLocalisation(value, new Locale("pl", "PL"))).isEqualTo("23 500,00 zł");

5. Advanced Formatting Use-Cases

DecimalFormat is one of the most popular ways to format a decimal number in Java. Similar to previous examples, we’ll write a helper method:

public static double withDecimalFormatLocal(double value)

Our type of formatting will get the default setting for a given localization.

The decimal formatting is handled differently in different countries using their numeric systems. This includes the grouping character (comma in the US, but space or dot in other locales), the grouping size (three in the US and most locales, but different in India), or the decimal character (dot in the US, but a comma in other locales).

double D = 4.2352989244d; assertThat(withDecimalFormatLocal(D)).isEqualTo(4.235);

We can also extend this functionality to provide some specific patterns:

public static double withDecimalFormatPattern(double value, int places) < DecimalFormat df2 = new DecimalFormat("#,###,###,##0.00"); DecimalFormat df3 = new DecimalFormat("#,###,###,##0.000"); if (places == 2) return new Double(df2.format(value)); else if (places == 3) return new Double(df3.format(value)); else throw new IllegalArgumentException(); >assertThat(withDecimalFormatPattern(D, 2)).isEqualTo(4.24); assertThat(withDecimalFormatPattern(D, 3)).isEqualTo(4.235);

Here we allow our user to configure DecimalFormat by chosen pattern based on the number of spaces.

6. Conclusion

In this article, we briefly explored different ways of number formatting in Java. As we can see, there’s no one best way to do this. Many approaches can be used, as each of them have their own characteristics.

As always, the code for these examples is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью