Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.vaadin.addons.dramafinder.element.utils;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class NumberUtils {

Expand All @@ -9,8 +11,11 @@ public static String formatDouble(double value) {
if (value == Math.rint(value)) {
return String.valueOf((long) value);
} else {
// Use DecimalFormat to avoid scientific notation
DecimalFormat df = new DecimalFormat("0.######");
// Use DecimalFormat to avoid scientific notation. Locale.ROOT keeps the
// decimal separator a "." regardless of the JVM default locale, matching
// what the browser reports for native input value/step/min/max.
DecimalFormat df = new DecimalFormat("0.######",
DecimalFormatSymbols.getInstance(Locale.ROOT));
return df.format(value);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package org.vaadin.addons.dramafinder.element.utils;

import java.util.Locale;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class NumberUtilsTest {

private final Locale defaultLocale = Locale.getDefault();
private final Locale defaultFormatLocale = Locale
.getDefault(Locale.Category.FORMAT);

@AfterEach
void restoreLocale() {
Locale.setDefault(defaultLocale);
Locale.setDefault(Locale.Category.FORMAT, defaultFormatLocale);
}

@Test
void formatDouble_wholeValue_noFractionalPart() {
assertEquals("5", NumberUtils.formatDouble(5d));
assertEquals("0", NumberUtils.formatDouble(0d));
assertEquals("-3", NumberUtils.formatDouble(-3d));
}

@Test
void formatDouble_fractionalValue_dotSeparator() {
assertEquals("0.5", NumberUtils.formatDouble(0.5));
assertEquals("5.5", NumberUtils.formatDouble(5.5));
assertEquals("-1.25", NumberUtils.formatDouble(-1.25));
}

@Test
void formatDouble_commaSeparatorLocale_stillUsesDot() {
Locale.setDefault(Locale.FRANCE);

assertEquals("0.5", NumberUtils.formatDouble(0.5));
assertEquals("5.5", NumberUtils.formatDouble(5.5));
}

@Test
void formatDouble_commaSeparatorFormatCategory_stillUsesDot() {
Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY);

assertEquals("0.5", NumberUtils.formatDouble(0.5));
}

@Test
void formatDouble_smallValue_noScientificNotation() {
assertEquals("0.000001", NumberUtils.formatDouble(0.000001));
}
}
Loading