Limit Formatted Measurement to 2 Digits

Limit formatted Measurement to 2 digits

You need to set the MeasurementFormatter property unitOptions to .providedUnit:

let beans = Measurement<UnitMass>(value: 20.22321, unit: .milligrams) // "20.22321 mg"
let formatter = MeasurementFormatter()
formatter.unitOptions = .providedUnit
formatter.numberFormatter.maximumFractionDigits = 2
let label = formatter.string(from: beans) // "20.22 mg"

Python3.x: Format Float to 2 Digits, Limit to 3 Decimal places

You should be able to do the following with .format():

print('{:0>2d}:{:0>2d}:{:06.3f}'.format(hours,minutes,seconds))

In particular, 0>2d forces the integers hours and minutes to be of length 2. Further, 06.3f implies that the entire float representation should be 6 characters long (including the '.') and have 3 decimal places to the right of the period.

Decimal format not limiting values to two decimal places

I am new to programming

So the first thing you need to learn is how to simplify the problem.

I want to limit the output of the result to two decimal place so it looks neater

So, forget about the rest of your application and learn how to do exactly that:

double value =  123.45678;
DecimalFormat decFormat = new DecimalFormat("0.00");
String formatted = decFormat.format(value);
System.out.println( formatted );

I am writing a java gui program which converts different units of measurement.

That is irrelevant to you question. As you can see from the above example you first test a new concept with hardcoded data.

Once you get that working, then you worry about the mathematical calculations to dynamically get the "value" that you want to format.

My output currently is too many decimal places

label.setText(Double.toString(result));
DecimalFormat decFormat = new DecimalFormat("0.00");
decFormat.format(result);

Do you see the problems with the above code?

  1. you set the text of the label BEFORE you format the result
  2. you don't assign the formatted text to a variable so that last statement doesn't do anything.

Limiting both the fractional and total number of digits when formatting a float for display

Here is how I implemented this in my code. I don't know how efficient it is, I hope not bad.

So I create a global NSNumberFormatter

NSNumberFormatter* numFormatter; 

and initialize it somewhere:

numFormatter=[[NSNumberFormatter alloc]init];

Then I format number with the following function:

- (NSString*)formatFloat:(Float32)number withOptimalDigits:(UInt8)optimalDigits maxDecimals:(UInt8)maxDecimals
{
NSString* result;
UInt8 intDigits=(int)log10f(number)+1;
NSLog(@"Formatting %.5f with maxDig: %d maxDec: %d intLength: %d",number,optimalDigits,maxDecimals,intDigits);

numFormatter.maximumFractionDigits=maxDecimals;
if(intDigits>=optimalDigitis-maxDecimals) {
numFormatter.usesSignificantDigits=YES;
numFormatter.maximumSignificantDigits=(intDigits>optimalDigits)?intDigits:optimalDigits;
} else {
numFormatter.usesSignificantDigits=NO;
}
result = [numFormatter stringFromNumber:[NSNumber numberWithFloat:number]];

return result;
}

Limit a double to two decimal places

Use NSNumberFormatter. See the Data Formatting Programming Guide's chapter on Number Formatters.

How to format numbers by prepending 0 to single-digit numbers?

Edit (2021):

It's no longer necessary to format numbers by hand like this anymore. This answer was written way-back-when in the distant year of 2011 when IE was important and babel and bundlers were just a wonderful, hopeful dream.

I think it would be a mistake to delete this answer; however in case you find yourself here, I would like to kindly direct your attention to the second highest voted answer to this question as of this edit.

It will introduce you to the use of .toLocaleString() with the options parameter of {minimumIntegerDigits: 2}. Exciting stuff. Below I've recreated all three examples from my original answer using this method for your convenience.

[7, 7.5, -7.2345].forEach(myNumber => {
let formattedNumber = myNumber.toLocaleString('en-US', {
minimumIntegerDigits: 2,
useGrouping: false
})
console.log(
'Input: ' + myNumber + '\n' +
'Output: ' + formattedNumber
)
})

How can I format a decimal to always show 2 decimal places?

I suppose you're probably using the Decimal() objects from the decimal module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)

If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:

Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?

A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None

The next question reads

Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?

If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimals with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str will work fine:

str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'

Formatting a number with exactly two decimals in JavaScript

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

Note that toFixed() returns a string.

IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.

For instance:

2.005.toFixed(2) === "2.00"

UPDATE:

Nowadays, you can use the Intl.NumberFormat constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.

const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});

console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"


Related Topics



Leave a reply



Submit