# float

A Java method to round a float value to the nearest one-half value alvin April 24, 2018 - 10:43am

As a quick note, here’s a Java method that will round a `float` to the nearest half value, such as 1.0, 1.5, 2.0, 2.5, etc.:

```/**
* converts as follows:
* 1.1  -> 1.0
* 1.3  -> 1.5
* 2.1  -> 2.0
* 2.25 -> 2.5
*/
public static float roundToHalf(float f) {
return Math.round(f * 2) / 2.0f;
}```

The comments show how this function converts the example `float` values to their nearest half value, so I won’t add any more details here. I don’t remember the origin of this algorithm — I just found it in some old code, thought it was clever, and thought I’d share it here.

## How to handle very large numbers in Scala (BigInt, BigDecimal)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.6, “Handling Very Large Numbers in Scala.”

## Problem

You’re writing a Scala application and need to use very large integer or decimal numbers.

## Solution

Use the Scala `BigInt` and `BigDecimal` classes. You can create a `BigInt`:

Scala: How to parse a number from a String alvin July 10, 2017 - 1:25pm

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.1, “Parsing a Number from a String.”

## Problem

You want to convert a `String` to one of Scala’s numeric types (`Byte`, `Double`, `Int`, `Float`, `Long`, `Short`).

## Java: How to round a float or double to an integer

Java math FAQ: How do I round a float or double to an integer in Java?

Solution: Use `Math.round()` to round a `float` (or `double`) to the nearest integer (`int`) in Java.

You can see how this works in the examples that follow, where the result is shown in the comment after each line:

## How to generate random numbers, characters, and sequences in Scala

Scala FAQ: How do I generate random numbers (or characters) in Scala, such as when testing an application, performing a simulation, and many other situations?

## Solution

Create random numbers with the Scala scala.util.Random class. You can create random integers: