HarmonyOS 7 实时汇率换算里的一便士误差
源码与 README见换汇尺完整工程。
把原始报价固定在同一个交易日,输入 100 欧元,目标选英镑。换汇尺第一次得到的是 83.75,按那天的参考报价用十进制手算则是 83.755。如果产品约定恰好半便士向上舍入,界面应该显示 83.76。这个差值只有一便士,排查时却必须同时回答两件事:显示的金额到底取自哪一批报价,计算过程中有没有在到达最后一位之前截断或舍入。
现场先把币对、输入金额、参考价和报价日同时记下来。重新请求网络只有确认当时报价没有变化的作用,不能证明显示值的算法正确。页面右侧单独保留报价日期与实际获取时间,左侧目标金额旁边显示目标货币。这样把同一份报价从界面带回代码时,能够直接比较 GBP 的原始值、预期的十进制结果以及计算函数返回的字符串,不必从一张只有最终数字的截图猜计算条件。

HarmonyOS 7 电脑模拟器窄窗全屏。100 欧元换英镑显示 83.76,向下滚动可查看报价信息。
从目标货币的最小单位反推计算
工程里负责金额的是 Rates.ets。五种报价都以欧元为基准,表里每一项的含义是一欧元可换多少目标币。人民币换日元时,先用持有金额除以人民币报价,换算成欧元,再乘日元报价。代码实际把两步写成一个有理数比例。若先把折成的欧元保留两位小数,一旦后面乘上日元报价,第一次舍入的误差还会被放大;把中间值留在分子和分母里,目标币种只需要做一次舍入。
下面是用于解决这次误差的完整金额函数与它的定点拆分过程。decimalPart 以小数位数决定比例尺,整数位与小数位拼成系数。例如 0.83755 拆成 83755 和 100000;输入 100.00 则拆成 10000 和 100。把角分也纳入比例尺以后,整除结果已经是目标货币的最小单位。剩余的小数只通过余数比较,看它是否已到分母的一半。入口依赖同文件里的货币定义和已校验的报价,后面两段给出这些数据怎样进来。
interface DecimalPart {
digits: bigint;
scale: bigint;
}
function decimalPart(value: string): DecimalPart {
const parts = value.split('.');
const decimals = parts.length === 2 ? parts[1] : '';
return { digits: BigInt(parts[0] + decimals), scale: BigInt(10) ** BigInt(decimals.length) };
}
export function formattedConversion(amount: string, snapshot: RateSnapshot, from: number, to: number): string {
const input = decimalPart(amount.trim());
const fromRate = decimalPart(snapshot.rates[from].toString());
const toRate = decimalPart(snapshot.rates[to].toString());
const decimals = CURRENCIES[to].decimals;
const unit = BigInt(10) ** BigInt(decimals);
const numerator = input.digits * toRate.digits * fromRate.scale * unit;
const denominator = input.scale * toRate.scale * fromRate.digits;
let rounded = numerator / denominator;
if ((numerator % denominator) * BigInt(2) >= denominator) {
rounded += BigInt(1);
}
if (decimals === 0) {
return rounded.toString();
}
const digits = rounded.toString().padStart(decimals + 1, '0');
return digits.slice(0, -decimals) + '.' + digits.slice(-decimals);
}

实际编辑器中的 Rates.ets。红框标出分子、分母以及最后一位的整数舍入。
用这一版代码算英镑时,分子为 837550000,分母为 100000,整除是 8375 个便士,余数为 50000。余数乘二与分母相等,结果加一个便士,再把字符串小数点插回倒数第二位的前面。未修版把乘积交给二进制浮点后直接格式化,模拟器上看到了 83.75。现在最终金额使用整数比较,旁边的六位参考换算率只是辅助读数。它没有参与最终计算,读者也不应从那一行截下的数字反算显示金额。
日元分支也在同一个函数里,位数在 CURRENCIES 里设为零,因此舍入完成后直接返回整数。英镑与人民币使用两位。填 100,从人民币换到日元,本次显示 2391;交换币种后仍拿 100 作输入,结果变为 4.18 元。交换的是输入和输出的币种索引,所以检验时需要固定输入。若拿上一次输出再反换,前一次按日元最小单位舍入的信息已经丢掉一部分,无法要求它精确返回输入。
启动后最容易把空字段误当成零。真正常见的操作是刚删完、准备重新键入金额,而报价仍然挂在页面右侧。组件入口先验金额,再确认有快照,然后才调用精确换算。readAmount 接受最多八位整数和四位小数,允许输入整数后的末尾小数点,避免打字过程中光标后刚输入小数点就让结果跳成错误提示。原始文本在校验后原样传给精确计算,校验阶段返回的 Number 值仅用于判定成功。
private result(): string {
const value = readAmount(this.amount);
if (value === null || !this.snapshot) {
return '—';
}
return formattedConversion(this.amount, this.snapshot, this.from, this.to);
}
一批报价如何成为一张可用快照
数据来自 Frankfurter 的参考汇率接口,请求限制数据源为欧洲央行,也限制基准币种和所需目标币种。解析过程先检查响应数组条数,再逐项核对基准币、日期、报价正值与目标币。这里不能只把数组逐项塞进界面:远端返回顺序应当与按钮定义无关,必须按币种查找相应位置。EUR 作为基准留在索引零,写入常量 1;英镑即使换一个客户请求顺序,也应取到属于英镑的值。
Rates.ets 可以独立跟读,它把原始回包、快照校验、交叉汇率和最终的分位舍入接成一条链。页面文件负责发起刷新、显示换算结果,以及网络失败后继续使用已验证的快照。
entry/src/main/ets/pages/Rates.ets
export interface Currency {
code: string;
name: string;
decimals: number;
}
export const CURRENCIES: Currency[] = [
{ code: 'EUR', name: '欧元', decimals: 2 },
{ code: 'USD', name: '美元', decimals: 2 },
{ code: 'CNY', name: '人民币', decimals: 2 },
{ code: 'JPY', name: '日元', decimals: 0 },
{ code: 'GBP', name: '英镑', decimals: 2 }
];
export const URL = 'https://api.frankfurter.dev/v2/rates?base=EUR"es=USD,CNY,JPY,GBP&providers=ecb';
interface QuoteRow {
date: string;
base: string;
quote: string;
rate: number;
}
export interface RateSnapshot {
date: string;
receivedAt: number;
rates: number[];
}
function validDate(value: string): boolean {
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);
}
function positiveRate(value: number): boolean {
return typeof value === 'number' && Number.isFinite(value) && value >= 0.000001 && value <= 1000000 &&
/^\d{1,7}(\.\d{1,10})?$/.test(value.toString());
}
export function decodeRates(raw: string): RateSnapshot {
if (raw.length > 100000) {
throw new Error('响应超过示例上限');
}
const rows = JSON.parse(raw) as QuoteRow[];
if (!Array.isArray(rows) || rows.length !== CURRENCIES.length - 1) {
throw new Error('响应未包含完整报价');
}
const rates: number[] = [1, 0, 0, 0, 0];
let date = '';
for (const row of rows) {
if (!row || row.base !== 'EUR' || !validDate(row.date) || !positiveRate(row.rate)) {
throw new Error('基准币、日期或报价无效');
}
const index = CURRENCIES.findIndex((currency: Currency): boolean => currency.code === row.quote);
if (index < 1 || rates[index] !== 0 || (date !== '' && date !== row.date)) {
throw new Error('报价重复、超出范围或日期不一致');
}
rates[index] = row.rate;
date = row.date;
}
if (!rates.every(positiveRate)) {
throw new Error('报价不完整');
}
return { date: date, receivedAt: Date.now(), rates: rates };
}
export function readSnapshot(raw: string): RateSnapshot | null {
if (!raw) {
return null;
}
const saved = JSON.parse(raw) as RateSnapshot;
if (!saved || !validDate(saved.date) || !Number.isFinite(saved.receivedAt) ||
!Array.isArray(saved.rates) || saved.rates.length !== CURRENCIES.length ||
saved.rates[0] !== 1 || !saved.rates.every(positiveRate)) {
return null;
}
return saved;
}
export function readAmount(value: string): number | null {
if (!/^\d{1,8}(\.\d{0,4})?$/.test(value.trim())) {
return null;
}
return Number(value.trim());
}
export function crossRate(snapshot: RateSnapshot, from: number, to: number): number {
return snapshot.rates[to] / snapshot.rates[from];
}
interface DecimalPart {
digits: bigint;
scale: bigint;
}
function decimalPart(value: string): DecimalPart {
const parts = value.split('.');
const decimals = parts.length === 2 ? parts[1] : '';
return { digits: BigInt(parts[0] + decimals), scale: BigInt(10) ** BigInt(decimals.length) };
}
export function formattedConversion(amount: string, snapshot: RateSnapshot, from: number, to: number): string {
const input = decimalPart(amount.trim());
const fromRate = decimalPart(snapshot.rates[from].toString());
const toRate = decimalPart(snapshot.rates[to].toString());
const decimals = CURRENCIES[to].decimals;
const unit = BigInt(10) ** BigInt(decimals);
const numerator = input.digits * toRate.digits * fromRate.scale * unit;
const denominator = input.scale * toRate.scale * fromRate.digits;
let rounded = numerator / denominator;
if ((numerator % denominator) * BigInt(2) >= denominator) {
rounded += BigInt(1);
}
if (decimals === 0) {
return rounded.toString();
}
const digits = rounded.toString().padStart(decimals + 1, '0');
return digits.slice(0, -decimals) + '.' + digits.slice(-decimals);
}
entry/src/main/ets/pages/Index.ets
import { common } from '@kit.AbilityKit';
import { preferences } from '@kit.ArkData';
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import {
CURRENCIES, Currency, RateSnapshot, URL, crossRate, decodeRates, formattedConversion, readAmount, readSnapshot
} from './Rates';
const INK = '#142723';
const SUB = '#455A54';
const ACCENT = '#155A4C';
const PAPER = '#F3F5EF';
const CACHE_KEY = 'reference-rates-v1';
@Entry
@Component
struct Index {
@State amount: string = '100';
@State from: number = 0;
@State to: number = 1;
@State snapshot: RateSnapshot | null = null;
@State status: string = '尚未取价';
@State detail: string = '';
@State busy: boolean = false;
@State cached: boolean = false;
@State widthVp: number = 900;
@State rotation: number = 0;
private store: preferences.Preferences | null = null;
private active: http.HttpRequest | null = null;
private revision: number = 0;
aboutToAppear(): void {
try {
const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
this.store = preferences.getPreferencesSync(context, { name: 'ratebench' });
this.snapshot = readSnapshot(String(this.store.getSync(CACHE_KEY, '')));
if (this.snapshot) {
this.cached = true;
this.status = '已读回上次报价';
hilog.info(0, 'RateBench', 'restored %{public}s', this.snapshot.date);
}
} catch (e) {
hilog.warn(0, 'RateBench', 'cache read failed: %{public}s', (e as Error).message);
}
this.refresh();
}
aboutToDisappear(): void {
this.revision++;
if (this.active) {
this.active.destroy();
}
}
private async refresh(testUnreachable: boolean = false): Promise<void> {
if (this.busy) {
return;
}
const ticket = ++this.revision;
const task = http.createHttp();
this.active = task;
this.busy = true;
this.detail = '';
this.status = '正在获取参考汇率';
try {
const response = await task.request(URL, {
method: http.RequestMethod.GET, expectDataType: http.HttpDataType.STRING,
usingCache: false, connectTimeout: 4500, readTimeout: 4500,
usingProxy: testUnreachable ? { host: '127.0.0.1', port: 1, exclusionList: [] } : false
});
if (ticket !== this.revision) {
return;
}
if (response.responseCode !== 200) {
throw new Error('HTTP ' + response.responseCode);
}
const next = decodeRates(response.result as string);
this.snapshot = next;
this.cached = false;
this.status = '已获取最新参考价';
hilog.info(0, 'RateBench', 'updated %{public}s', JSON.stringify(next));
this.flushSnapshot(next);
} catch (e) {
if (ticket !== this.revision) {
return;
}
const fault = e as BusinessError;
this.cached = this.snapshot !== null;
this.status = this.snapshot ? '刷新失败 · 沿用上次报价' : '暂时无法获取报价';
this.detail = fault.code ? '网络错误 ' + String(fault.code) : (fault.message || '请求失败');
hilog.warn(0, 'RateBench', 'refresh failed %{public}s', this.detail);
} finally {
if (ticket === this.revision) {
task.destroy();
this.active = null;
this.busy = false;
}
}
}
private async flushSnapshot(value: RateSnapshot): Promise<void> {
if (!this.store) {
return;
}
try {
this.store.putSync(CACHE_KEY, JSON.stringify(value));
await this.store.flush();
} catch (e) {
hilog.warn(0, 'RateBench', 'cache write failed: %{public}s', (e as Error).message);
}
}
private swap(): void {
this.getUIContext().animateTo({ duration: 350, curve: Curve.EaseInOut }, (): void => {
const prior = this.from;
this.from = this.to;
this.to = prior;
this.rotation += 180;
});
}
private result(): string {
const value = readAmount(this.amount);
if (value === null || !this.snapshot) {
return '—';
}
return formattedConversion(this.amount, this.snapshot, this.from, this.to);
}
private receivedAt(): string {
return this.snapshot ? new Date(this.snapshot.receivedAt).toISOString().replace('T', ' ').slice(0, 19) + ' UTC' : '—';
}
@Builder currencyGroup(isFrom: boolean, label: string) {
Column({ space: 8 }) {
Text(label).fontColor(SUB).fontSize(14).fontWeight(FontWeight.Medium)
Row({ space: 6 }) {
ForEach(CURRENCIES, (item: Currency, index: number) => {
Button(item.code)
.id((isFrom ? 'from-' : 'to-') + item.code)
.layoutWeight(1)
.fontSize(14)
.height(40)
.padding(0)
.fontColor((isFrom ? this.from : this.to) === index ? '#FFFFFF' : INK)
.backgroundColor((isFrom ? this.from : this.to) === index ? ACCENT : '#E9EDE6')
.borderRadius(10)
.accessibilityText(item.name + ' ' + item.code)
.onClick((): void => {
this.getUIContext().animateTo({ duration: 280, curve: Curve.EaseOut }, (): void => {
if (isFrom) {
this.from = index;
} else {
this.to = index;
}
});
})
}, (item: Currency): string => item.code)
}.width('100%')
}.alignItems(HorizontalAlign.Start).width('100%')
}
@Builder converter() {
Column({ space: 16 }) {
Text('换算').fontSize(22).fontWeight(FontWeight.Bold).fontColor(INK)
this.currencyGroup(true, '持有币种')
this.currencyGroup(false, '目标币种')
Row({ space: 10 }) {
TextInput({ text: this.amount, placeholder: '输入金额' })
.id('amount').layoutWeight(1).height(47).fontSize(19).fontColor(INK)
.type(InputType.NUMBER_DECIMAL).maxLength(13).backgroundColor(PAPER)
.onChange((value: string): void => { this.amount = value; })
Button('⇄').fontSize(26).fontColor(ACCENT).backgroundColor('#E3F0EA').width(54).height(47)
.rotate({ angle: this.rotation }).id('swap').accessibilityText('交换两个币种').onClick(() => this.swap())
}.width('100%')
if (readAmount(this.amount) === null) {
Text('请输入最多 8 位整数、4 位小数的金额').fontSize(13).fontColor('#8C491F').id('invalid')
}
Column({ space: 5 }) {
Text('换算结果 · ' + CURRENCIES[this.to].code).fontSize(13).fontColor('#D3F0E5').id('target-symbol')
Text(this.result()).fontSize(this.widthVp < 720 ? 32 : 40)
.fontWeight(FontWeight.Bold).fontColor('#FFFFFF').maxLines(1)
.minFontSize(18).maxFontSize(40).id('result')
Text(this.snapshot ? '1 ' + CURRENCIES[this.from].code + ' ≈ ' +
crossRate(this.snapshot, this.from, this.to).toFixed(6) + ' ' + CURRENCIES[this.to].code : '等待参考报价')
.fontColor('#D3F0E5').fontSize(13).id('quote-line')
}.alignItems(HorizontalAlign.Start).width('100%').padding(17).backgroundColor(ACCENT).borderRadius(14)
}.alignItems(HorizontalAlign.Start).padding(20).backgroundColor('#FFFFFF').borderRadius(18).width('100%')
}
@Builder sourcePanel() {
Column({ space: 11 }) {
Text('参考报价').fontSize(22).fontWeight(FontWeight.Bold).fontColor(INK)
Text(this.status).fontSize(17).fontWeight(FontWeight.Bold)
.fontColor(this.cached || this.detail ? '#8C491F' : ACCENT).id('status')
Text('报价日 ' + (this.snapshot?.date || '—')).fontSize(15).fontColor(SUB).id('quote-date')
Text('最近获取 ' + this.receivedAt()).fontSize(14).fontColor(SUB).id('received-at')
Text('欧洲央行参考价 · Frankfurter').fontSize(13).fontColor(SUB).id('provider')
if (this.detail) {
Text(this.detail).fontSize(13).fontColor('#8C491F').id('failure-detail')
}
Button('刷新参考价').id('refresh').height(42).backgroundColor(ACCENT).fontColor('#FFFFFF')
.enabled(!this.busy).onClick(() => this.refresh())
Button('测试连接失败').id('failure-test').height(38).backgroundColor('#E9EDE6').fontColor(INK)
.enabled(!this.busy).onClick(() => this.refresh(true))
}.alignItems(HorizontalAlign.Start).padding(20).backgroundColor('#FFFFFF').borderRadius(18).width('100%')
}
build() {
Scroll() {
Column({ space: 18 }) {
Text('换汇尺').fontSize(34).fontColor(INK).fontWeight(FontWeight.Bold).id('app-title')
if (this.widthVp >= 720) {
Row({ space: 16 }) {
Column() { this.converter() }.layoutWeight(3)
Column() { this.sourcePanel() }.layoutWeight(2)
}.alignItems(VerticalAlign.Top).width('100%')
} else {
this.converter()
this.sourcePanel()
}
}.alignItems(HorizontalAlign.Start).padding(23).width('100%').constraintSize({ maxWidth: 1240 })
}
.width('100%').height('100%').backgroundColor(PAPER).scrollable(ScrollDirection.Vertical)
.id('workbench').onAreaChange((_old: Area, area: Area): void => { this.widthVp = Number(area.width); })
}
}
所有子项到齐之后才给快照赋获取时间。假定网络一切正常,但某一轮响应中英镑缺失,或者同批出现两个日期,左边报价单和右边的日期就无法描述同一批数据。代码选择将整批判为失败,保持先前的完整快照。在出错时把四个有效报价和一行空白合并到旧状态,选用户看不到的条件下会让换算仍然有数字,却无法追溯那个数字是否来自同一天。
回答金额为何改变,先比较报价日和币对,再比较获取时间。前者来自数据,后者是应用验证接受这批数据的时间,在界面里以 UTC 标明。连续点正常刷新,日期可能维持在 2026-11-26,获取时间仍可更新。这说明接口又返回了该日参考价。工作日和休息日之间可能没有新报价,页面不会因为到点刷新就自行增加一个交易日。换汇尺适合做金额估算,实际成交仍要看交易机构的报价与费用。

HarmonyOS 7 电脑模拟器宽窗全屏。在线取得报价时同时显示金额、报价日与获取时间。
主动触发一次请求失败,检查旧数据留在什么位置
联网方法在 Index.ets。组件保存了刷新是否在进行、当前 HTTP 对象和请求序号。请求进行中按钮不可用,避免一次反复点击制造多个更新。请求序号则覆盖页面退出的情形:离开时增加序号并销毁请求,异步任务仍可能在销毁之后返回,此时成功与失败分支都不应该改动已离开的界面。这里将 createHttp 之后的成功、拒绝和清理路径放在一段里,便于顺着调用对照。
aboutToDisappear(): void {
this.revision++;
if (this.active) {
this.active.destroy();
}
}
private async refresh(testUnreachable: boolean = false): Promise<void> {
if (this.busy) {
return;
}
const ticket = ++this.revision;
const task = http.createHttp();
this.active = task;
this.busy = true;
this.detail = '';
this.status = '正在获取参考汇率';
try {
const response = await task.request(URL, {
method: http.RequestMethod.GET, expectDataType: http.HttpDataType.STRING,
usingCache: false, connectTimeout: 4500, readTimeout: 4500,
usingProxy: testUnreachable ? { host: '127.0.0.1', port: 1, exclusionList: [] } : false
});
if (ticket !== this.revision) {
return;
}
if (response.responseCode !== 200) {
throw new Error('HTTP ' + response.responseCode);
}
const next = decodeRates(response.result as string);
this.snapshot = next;
this.cached = false;
this.status = '已获取最新参考价';
hilog.info(0, 'RateBench', 'updated %{public}s', JSON.stringify(next));
this.flushSnapshot(next);
} catch (e) {
if (ticket !== this.revision) {
return;
}
const fault = e as BusinessError;
this.cached = this.snapshot !== null;
this.status = this.snapshot ? '刷新失败 · 沿用上次报价' : '暂时无法获取报价';
this.detail = fault.code ? '网络错误 ' + String(fault.code) : (fault.message || '请求失败');
hilog.warn(0, 'RateBench', 'refresh failed %{public}s', this.detail);
} finally {
if (ticket === this.revision) {
task.destroy();
this.active = null;
this.busy = false;
}
}
}

实际编辑器中的 Index.ets。请求失败时保留原有快照,状态区显示故障详情。
故障按钮只给这一条请求指定回环地址的不可用代理。实际 HTTP 请求在连接阶段报错,应用捕获的是网络栈返回的错误,并未在按钮处理函数里直接修改文案来假装失败。其他网络请求没有一起被切断,移除这个请求专用代理后即可用原路径重新刷新。观察时把币种停在日元对人民币,故障前的金额、日期和获取时刻都写下来,再按按钮。结果保持为 4.18,状态显示沿用上次报价,下面多出真实错误 2300007。正常刷新以后该提示消失。

HarmonyOS 7 模拟器请求失败后仍显示 4.18 元人民币,报价区明确标为沿用上次报价。
与当前页面复用同一对象的失败回退相比,重启要从 Preferences 读回曾经写入的整个快照。写入方法把已验证对象编码成一条字符串,再调用 flush。页面重建后用 readSnapshot 检查日期、获取时间、数组长度及每项是否可用于计算。预先从存储读回成功,在线刷新便可以继续进行,不必让用户先对着一块金额空白等待。存储写入失败只记录日志,已经获得的在线报价在本次页面仍可用,下次启动则只能读到上一次真正保存的快照。
private async flushSnapshot(value: RateSnapshot): Promise<void> {
if (!this.store) {
return;
}
try {
this.store.putSync(CACHE_KEY, JSON.stringify(value));
await this.store.flush();
} catch (e) {
hilog.warn(0, 'RateBench', 'cache write failed: %{public}s', (e as Error).message);
}
}
aboutToAppear(): void {
try {
const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
this.store = preferences.getPreferencesSync(context, { name: 'ratebench' });
this.snapshot = readSnapshot(String(this.store.getSync(CACHE_KEY, '')));
if (this.snapshot) {
this.cached = true;
this.status = '已读回上次报价';
hilog.info(0, 'RateBench', 'restored %{public}s', this.snapshot.date);
}
} catch (e) {
hilog.warn(0, 'RateBench', 'cache read failed: %{public}s', (e as Error).message);
}
this.refresh();
}
两个入口复用同一批报价的数据类型,校验重点却有区别。联网解析的是四条带币种的响应,需要判断币种映射和日期一致性。磁盘恢复的是已经编排好的数组,数组里的第一项必须还是 1,其余项目要满足报价范围。aboutToAppear 在开始在线请求之前执行这次同步读回;即使 JSON 损坏抛异常,外层捕获之后也会走 refresh。排查缓存时,可以从这段代码分清空存储、格式被拒绝和读盘异常。当前存储按一个键保存整批,不提供多日查询,也没有单独为每个货币维护有效期。
复测重开时,看到日志先出现 restored 再出现 updated,用以区分读回和联网两个过程。只看重开后最终仍出现数字,无法区分它是缓存还是刚下载下来的;因此要同时读页面状态和日志。宽窗用并排面板,窄窗把源数据排在金额卡下方,仍然保留日期和状态入口。切窗后继续用同一笔输入验证,也验证了换布局没有把选择或报价状态重建为默认值。

HarmonyOS 7 模拟器实录。选币、交换方向,触发请求失败后沿用报价,再恢复正常刷新。
复跑时让每个结果都能说明一件事
从源码直链取本文版本,用 DevEco 打开该独立工程,确认 entry 支持 2in1 并声明网络权限。在项目目录同步依赖,选鸿蒙 7 电脑模拟器运行 entry。以下命令等价于构建该模块的调试包;包路径、可安装的调试环境和需要手动选择设备的操作在同目录 README 里。安装后先做正常取价,实测数字随报价日变化,只有拿到同一批报价时才逐数字对照本文金额。
ohpm install --all
hvigorw --mode module -p module=entry@default -p product=default -p requiredDeviceType=2in1 -p buildMode=debug assembleHap
如果复现日期已经跨月,仍可以验证舍入改动。有现成的 RateSnapshot 类型,直接把表中这一批数据按源码索引填进快照,再将金额字符串传给 formattedConversion。这个检验不依赖外部服务,变更显示层时也可以用它排除算术回归。要验联网解析则需让响应真的经过 decodeRates,仅写一个计算用快照无法验证响应形状或缓存回退。两条路径分开比较,可以在网络不稳定时先确认计算代码,再用在线结果补齐实际接入的证据。
| 操作 | 本轮观察 | 判据 |
|---|---|---|
| 取价后算 100 EUR → USD | 109.75 USD | 2026-11-26 的参考价为 1.0975 |
| 选 CNY → JPY 再交换 | 2391 JPY,再变为 4.18 CNY | 输入同为 100,目标定位与小数位换了 |
| 故障按钮,再正常刷新 | 2300007,保留 4.18,后续正常刷新 | 失败未改动报价日与获取时间 |
| 结束进程并重开 | 先 restored 后 updated | 已确认读回快照 |
| 缩窄后选 EUR → GBP | 83.76 GBP | 同一报价,验证精确半进位;宽度从 2090 px 到 1271 px |
保留报价日,再比较不同轮次的两笔结果
我先用源码中的 formattedConversion 重算文首样本。单独给函数输入 100 欧元与固定参考价 0.83755,返回 83.76 英镑。真机重新联网时使用的是 2026-11-30 报价。100 欧元换成美元为 108.94,改目标为英镑后为 83.49。两笔英镑数值的原始报价处在不同轮次,复核舍入时各自按页面标明的日期对照。

MatePad Edge 电脑模式。选 EUR 到 GBP 后,2026-11-30 报价显示 100 欧元换算为 83.49 英镑。
真机测试连接失败时返回 2300007,界面仍沿用此前的美元结果,报价日和最近获取时间都保持第一次读数。随后再点刷新,恢复成功,最近获取时间从 15:14:54 UTC 变为 15:15:00 UTC,报价日和 108.94 的换算本轮保持相同。Network Kit 负责请求,ArkData Preferences 用于保存最后一次成功快照。

MatePad Edge 真机全屏。连接失败后,结果、报价日和旧获取时间继续显示。

从同一份美元报价出发,触发连接失败、恢复正常请求,再切到英镑。
| 结果对应 | 验证环境 |
|---|---|
| 2026-11-30 真机联网报价 | HUAWEI MatePad Edge(QXS-W00)电脑模式,tablet,arm64-v8a。HarmonyOS 7.0.0.111(SP18C00E111R6P5patch02),API 26 |
| 前文原模拟器样本 | MateBook Pro 电脑模拟器,2-in-1,x86_64。HarmonyOS 7.0.0.107(SP8DEVC00E47R1P3),API 26 |
| 构建和签名 | DevEco Studio 6.1.1.300;DevEco 命令行工具 26.0.0.865、SDK 26.0.0.105、Hvigor 6.26.9。tablet 签名调试包经 USB HDC 安装 |

本轮查取参考报价使用的 MatePad Edge 系统版本。

编译这只调试 HAP 的 DevEco Studio 版本页。
| 项目 | 实际环境 |
|---|---|
| 工具与 SDK | Windows,DevEco 命令行工具 26.0.0.865,HarmonyOS SDK 26.0.0.105 |
| 兼容与目标 | API 26 / API 26 |
| 设备 | MateBook Pro 电脑模拟器(2-in-1),x86_64,3120 × 2080 |
| 运行系统 | HarmonyOS 7.0.0.107(SP8DEVC00E47R1P3) |
| 应用 | com.aasd23.p6ratebench,1.0.0 |

本轮鸿蒙 7 电脑模拟器原生关于本机界面,序列号已遮盖。
FAQ
刚装好就点故障测试,怎样检查回退?
先等一次正常取价,记下右侧报价日和获取时间,再触发故障。空安装最初连不上时,页面只会报告暂时无法取价,金额显示短横线。这个用例验证空态,不能证明缓存回退。要检查真正写入存储的结果,就在正常刷新后退出重开并查日志;只在同一个窗口里反复切换币种能说明内存里的快照可继续算。
正常刷新报错,能用 2300007 判定服务器宕机吗?
这个错误是指定了不可达代理后记录的连接故障。普通刷新也出错时,先区分是 HTTP 连接没有建立、收到非成功状态码,还是请求成功后内容校验抛错。依靠状态和 RateBench 日志定位,另外用同一网络查看引用的接口和数据源。只有当前报价成功解析,应用才会把它交给换算页面。
写一个同样的换算器时,小数规则从哪里开始改?
先明确业务要保留哪种货币的最小单位、恰好一半时如何处理、是否允许负数。本例金额格式仅接受非负十进制输入,报价为正,整数除法的余数比较建立在这个前提上。如果要支持退款负数或半偶舍入,应给新的舍入规则单独写用例。至少固定一组让结果恰好落在两档之间的数据,再加入靠近两侧的值,由这些可以手算的输入判定应显示的字符串。
一便士的用例把显示层、计算层和报价状态放在了同一条检查线上。修复以后,同一结构的报价可以追到实际交易日,金额计算只取最后一位的舍入,遇到连接失败也能读出当前是哪个状态。以后替换数据提供方时,先用这条检查线核对报价基准和小数精度,再决定现有的解析和算术实现哪些能沿用。
参考资料见Frankfurter 接口文档、欧洲央行参考汇率。
更多推荐

所有评论(0)