gpt4 book ai didi

Java Swing - 本地化温度

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:53 24 4
gpt4 key购买 nike

有没有办法在 Java 中本地化 Temperature?像温度格式将基于语言环境?

因为例如,挪威语的温度格式应为 14 °C。度数符号前应有一个空格。但其他语言应为 14°C。

最佳答案

以下示例演示了温度本地化,包括通过区域设置特定属性自定义的舍入和十进制值格式。

public class LocalTemperature {

private final Locale locale;
private final String temperatureFormat;
private final float conversionFactor;
private final float conversionOffset;

public LocalTemperature(ResourceBundle bundle) {
locale = bundle.getLocale();
temperatureFormat = bundle.getString("temperature.decimal.format");
conversionFactor = Float.parseFloat(bundle.getString("temperature.conversion.factor"));
conversionOffset = Float.parseFloat(bundle.getString("temperature.conversion.offset"));
}

public String format(double kelvin) {
double localTemperature = conversionOffset + conversionFactor * kelvin;

DecimalFormat format = new DecimalFormat(temperatureFormat, DecimalFormatSymbols.getInstance(locale));

return format.format(localTemperature);
}
}

MyResources_DE.properties:

temperature.conversion.factor=1.0
temperature.conversion.offset=-273.15
temperature.decimal.format=###,###.##°C

MyResources_NR.properties:

temperature.conversion.factor=1.0
temperature.conversion.offset=-273.15
temperature.decimal.format=###,###.## °C

MyResources_en_US.properties:

temperature.conversion.factor=1.8
temperature.conversion.offset=-459.67
temperature.decimal.format=###,###.## °F

这可以通过以下单元测试来验证:

@RunWith(Parameterized.class)
public class LocalTemperatureTest {

private final double testValue;
private final String expectedResult;
private final LocalTemperature testSubject;


public LocalTemperatureTest(Locale locale, double testValue, String expected) {
ResourceBundle bundle = ResourceBundle.getBundle("MyResources", locale);

this.testSubject = new LocalTemperature(bundle);
this.testValue = testValue;
this.expectedResult = expected;
}

@Test
public void test() {
TestCase.assertEquals("Conversion error", expectedResult, testSubject.format(testValue));
}

@Parameters(name="{index}: locale={0} kelvin={1} expected={2}")
public static Iterable<Object[]> getTestParameters() {
Locale norwegian = new Locale("nr");

Object[][] parameters = {
{Locale.GERMAN, 0, "-273,15°C"},
{Locale.GERMAN, 273.15, "0°C"},
{Locale.GERMAN, 287.15, "14°C"},
{Locale.GERMAN, 287.35, "14,2°C"},
{Locale.GERMAN, 287.38, "14,23°C"},
{Locale.GERMAN, 287.384, "14,23°C"},
{Locale.GERMAN, 287.385, "14,24°C"},
{norwegian, 287.15, "14 °C"},
{Locale.US, 300.0, "80.33 °F"}
};
return Arrays.asList(parameters);
}
}

请注意,根据契约(Contract),所有提供的温度值都应具有相同的基准刻度(此处为开尔文)。

关于Java Swing - 本地化温度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41545466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com