Format a Number as 2.5K If a Thousand or More, Otherwise 900

Format a number as 2.5K if a thousand or more, otherwise 900

Sounds like this should work for you:

function kFormatter(num) {    return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)}    console.log(kFormatter(1200)); // 1.2kconsole.log(kFormatter(-1200)); // -1.2kconsole.log(kFormatter(900)); // 900console.log(kFormatter(-900)); // -900

Format a number as 2.5K if a thousand or more, otherwise 900

Sounds like this should work for you:

function kFormatter(num) {    return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)}    console.log(kFormatter(1200)); // 1.2kconsole.log(kFormatter(-1200)); // -1.2kconsole.log(kFormatter(900)); // 900console.log(kFormatter(-900)); // -900

How to format numbers in thousands, million or billions in vue.js?

I found two npm packages that seem to do the trick:

https://www.npmjs.com/package/number-shortener

This first one doesn't seem very widely used, but looking at the code it's very lightweight.

The second is:

https://www.npmjs.com/package/number-abbreviate

More popular and also very lightweight. I guess read and play around to see which one suits you better.

Convert long number into abbreviated string in JavaScript, with a special shortness requirement

I believe ninjagecko's solution doesn't quite conform with the standard you wanted. The following function does:

function intToString (value) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor((""+value).length/3);
var shortValue = parseFloat((suffixNum != 0 ? (value / Math.pow(1000,suffixNum)) : value).toPrecision(2));
if (shortValue % 1 != 0) {
shortValue = shortValue.toFixed(1);
}
return shortValue+suffixes[suffixNum];
}

For values greater than 99 trillion no letter will be added, which can be easily fixed by appending to the 'suffixes' array.

Edit by Philipp follows: With the following changes it fits with all requirements perfectly!

function abbreviateNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortValue = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}

How to format a big number with different bigmarks for thousand and millions (i.e. 1'000,000) in R

I would write my own function to do that, check the logic here.

custom_format <- function(number, msep = "'", tsep = ",") {
number = format(number, scientific = FALSE)

dplyr::case_when(
# for millions
nchar(number) <= 9 & nchar(number) > 6 ~
stringr::str_replace(
number,
"([0-9]+)([0-9]{3})([0-9]{3})$",
paste0("\\1", msep, "\\2", tsep, "\\3")
),
nchar(number) <= 6 & nchar(number) > 3 ~
stringr::str_replace(
number,
"([0-9])([0-9]{3})$",
paste0("\\1", tsep, "\\2")
),
nchar(number) <= 3 ~ number,
# For Thousands
TRUE ~ number
)
}

number <- c(10, 1500, 1000, 1000000, 23000, 234000000)
purrr::map_chr(number, custom_format)
#> [1] "10" "1,500" "1,000" "1'000,000" "23,000"
#> [6] "234'000,000"

Created on 2022-09-29 by the reprex package (v2.0.1)

Format a number 1000 as 1k, 1000000 as 1m etc. in R

Using dplyr::case_when:

so_formatter <- function(x) {
dplyr::case_when(
x < 1e3 ~ as.character(x),
x < 1e6 ~ paste0(as.character(x/1e3), "K"),
x < 1e9 ~ paste0(as.character(x/1e6), "M"),
TRUE ~ "To be implemented..."
)
}

test <- c(1, 999, 1000, 999000, 1000000, 1500000, 1000000000, 100000000000)
so_formatter(test)

# [1] "1"
# [2] "999"
# [3] "1K"
# [4] "999K"
# [5] "1M"
# [6] "1.5M"
# [7] "To be implemented..."
# [8] "To be implemented..."

How to go about formatting 1200 to 1.2k in java

Here is a solution that works for any long value and that I find quite readable (the core logic is done in the bottom three lines of the format method).

It leverages TreeMap to find the appropriate suffix. It is surprisingly more efficient than a previous solution I wrote that was using arrays and was more difficult to read.

private static final NavigableMap<Long, String> suffixes = new TreeMap<> ();
static {
suffixes.put(1_000L, "k");
suffixes.put(1_000_000L, "M");
suffixes.put(1_000_000_000L, "G");
suffixes.put(1_000_000_000_000L, "T");
suffixes.put(1_000_000_000_000_000L, "P");
suffixes.put(1_000_000_000_000_000_000L, "E");
}

public static String format(long value) {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
if (value < 0) return "-" + format(-value);
if (value < 1000) return Long.toString(value); //deal with easy case

Entry<Long, String> e = suffixes.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();

long truncated = value / (divideBy / 10); //the number part of the output times 10
boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}


Test code

public static void main(String args[]) {
long[] numbers = {0, 5, 999, 1_000, -5_821, 10_500, -101_800, 2_000_000, -7_800_000, 92_150_000, 123_200_000, 9_999_999, 999_999_999_999_999_999L, 1_230_000_000_000_000L, Long.MIN_VALUE, Long.MAX_VALUE};
String[] expected = {"0", "5", "999", "1k", "-5.8k", "10k", "-101k", "2M", "-7.8M", "92M", "123M", "9.9M", "999P", "1.2P", "-9.2E", "9.2E"};
for (int i = 0; i < numbers.length; i++) {
long n = numbers[i];
String formatted = format(n);
System.out.println(n + " => " + formatted);
if (!formatted.equals(expected[i])) throw new AssertionError("Expected: " + expected[i] + " but found: " + formatted);
}
}

Text expander paste function to format a phone number

Add the +1 to your regex, but don't include it in a group:
/^\+1(\d{3})(\d{3})(\d{4})$/

regexer can be super helpful for flushing these issues out~

c# textbox number format without lose its first value

NumericUpDown

The NumericUpDown is supposed to be the default choice for this problem where you can keep the real value and control what to display. In your case, set the DecimalPlaces property to 0 (the default value) and set the Minimum and Maximum properties to the Decimal.MinValue and Decimal.MaxValue respectively.

public YourForm()
{
InitializeComponent();

numericUpDown1.Maximum = decimal.MaxValue;
numericUpDown1.Minimum = decimal.MinValue;
numericUpDown1.DecimalPlaces = 0; // Default...

// The same for the other numeric controls...
}

Or, subclass to set the default values:

public class MyNumericUpDown : NumericUpDown
{
public MyNumericUpDown()
{
Minimum = decimal.MinValue;
Maximum = decimal.MaxValue;
}

/// <inheritdoc cref="NumericUpDown.Minimum"/>
[DefaultValue(typeof(decimal), "-79228162514264337593543950335")]
public new decimal Minimum { get => base.Minimum; set => base.Minimum = value; }

/// <inheritdoc cref="NumericUpDown.Maximum"/>
[DefaultValue(typeof(decimal), "79228162514264337593543950335")]
public new decimal Maximum { get => base.Maximum; set => base.Maximum = value; }
}

SOQ68431065A


TextBox

If the spin box is not an option and you need to use a TextBox. Create a new class and inherit the TextBox control, add a decimal property to store the real value and use it's setter to assign the integral part of the value to the Text property. Also you need to override the OnValidating method to validate the inputs as shown below if you allow text edit/paste.

[DefaultEvent("ValueChanged")]
[DefaultProperty("Value")]
[DesignerCategory("Code")]
public class IntTextBox : TextBox
{
public IntTextBox() : base()
{
//Comment if you allow text edit/paste...
ReadOnly = true;
BackColor = SystemColors.Window;
}

private decimal _value;
[DefaultValue(typeof(decimal), "0")]
public decimal Value
{
get => _value;
set
{
if (_value != value)
{
_value = value;
Text = Math.Truncate(value).ToString();
OnValueChanged(EventArgs.Empty);
}
}
}

protected override void OnValidating(CancelEventArgs e)
{
base.OnValidating(e);

if (ReadOnly) return;
// Change as required...
if (Text.Trim().Length == 0) Value = 0;
else if (decimal.TryParse(Text, out var res))
{
if (res % 1 != 0 && res != _value) Value = res;
else if (res != Math.Truncate(_value)) Value = res;
}
else
Text = Math.Truncate(Value).ToString();
}

// Handle this in the host instead of the TextChanged event if you need so...
public event EventHandler ValueChanged;

protected virtual void OnValueChanged(EventArgs e) =>
ValueChanged?.Invoke(this, e);
}

SOQ68431065B

Using this custom TextBox, forget the Text property and use instead the Value property to set/get the values.



Related Topics



Leave a reply



Submit